算法课第十八周Same Tree
来源:互联网 发布:乐视手机mac 编辑:程序博客网 时间:2024/06/07 20:52
Same TreeGiven two binary trees, write a function to check if they are equal or not.Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
解题思路:
给定两个树,判断这两个树是不是一模一样的树。
分析树的结构,用分治的思想,先判断val是否一样,再判断两个左边部分和两个右边部分是否一样。
先判断TreeNode是否是NULL,如果不是,将左边部分和右边部分视为另外的树,采用迭代的方法,再次判断val和比较左右两部分。如果两个左边的TreeNode是空,则判断右边的树是否一样即可,反之亦然。
class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if(p == NULL && q == NULL) return true; else if (p == NULL || q == NULL) return false; if(p->left == NULL && p->right == NULL && q->left == NULL && q->right == NULL) { if(p->val == q->val) return true; else return false; } else if (p->val == q->val && p->left == NULL && p->right != NULL && q->left == NULL && q->right != NULL) { return isSameTree(p->right, q->right); } else if (p->val == q->val && p->left != NULL && p->right == NULL && q->left != NULL && q->right == NULL) { return isSameTree(p->left, q->left); } else if (p->val == q->val && p->left != NULL && p->right != NULL && q->left != NULL && q->right != NULL) { return (isSameTree(p->left, q->left) && isSameTree(p->right, q->right)); } else return false; } };
阅读全文
0 0
- 算法课第十八周Same Tree
- 算法课第十七周作业 | Same Tree
- 算法:Same Tree
- 算法6 Same Tree
- 第六周Same Tree
- 算法课第2周第1题——100. Same Tree
- LeetCode Same Tree OJ 算法 刷题
- 【算法作业4】LeetCode 100. Same Tree
- 算法作业HW28:LeetCode 100. Same Tree
- 15算法课程 100. Same Tree
- 算法第十八周作业01
- 第八周:100. Same Tree
- 第十八周:110. Balanced Binary Tree
- 算法课第十八周作业 | Course Schedule II
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- JavaScript学习笔记之JSON&Ajax
- 算法--冒泡排序原理
- Google 推出的 Java 编码规范
- Java卡应用开发其实并不难(4)-第一个Java卡应用的调试
- 习题5-7 打印队列(Printer Queue, UVa12100)
- 算法课第十八周Same Tree
- CJOJ 1071 【Uva】硬币问题
- 现阶段选择ArcMap还是ArcGIS Pro
- python入门简易教程
- listner监听器 ___计算系统当前在线人数(解决浏览器关闭不调用sessionDestroyed方法)
- c语言之数组指针
- 鼠标移动上鼠标指针各种变化
- Linux下mysleep的实现
- HDU 1026 Ignatius and the Princess I (bfs+手写队列保存路径)