等价二叉树
来源:互联网 发布:获取当前系统时间 java 编辑:程序博客网 时间:2024/06/06 07:04
题目:
检查两棵二叉树是否等价。等价的意思是说,首先两棵二叉树必须拥有相同的结构,并且每个对应位置上的节点上的数都相等。
样例
1 1 / \ / \ 2 2 and 2 2 / /4 4
就是两棵等价的二叉树。
1 1 / \ / \ 2 3 and 2 3 / \4 4
就不是等价的。
思路:
两颗树相同的位置一个是空一个不是空或者两个的数值不同就不是等价二叉树,依次查看节点的左子树和右子树进行比较。如果遍历完没有不一样的就是等价二叉树。
代码:
class Solution {
public:
/**
* @aaram a, b, the root of binary trees.
* @return true if they are identical, or false.
*/
bool isIdentical(TreeNode* a, TreeNode* b) {
// Write your code here
if(a==NULL&&b==NULL) return true;
if(a==NULL&&b!=NULL||a!=NULL&&b==NULL||a->val!=b->val)
return false;
return isIdentical(a->left,b->left)&&isIdentical(a->right,b->right);
}
};
感想:
这个题还是较为容易的,只需要判读不是的情况即可,另外还要处理两个都是空的特殊情况。
0 0
- LintCode_469_等价二叉树
- LintCode:等价二叉树
- lintcode ----等价二叉树
- 等价二叉树
- 等价二叉树-lintcode
- 等价二叉树,lintcode
- lintcode-->等价二叉树
- lintcode,等价二叉树
- 等价二叉树
- LintCode-等价二叉树
- 等价二叉树
- 等价二叉树
- 等价二叉树
- LIntCode 等价二叉树
- 等价二叉树
- 等价二叉树-LintCode
- 等价二叉树
- 等价二叉树
- hdu2055 两个ac代码和一个无法ac的代码
- 九度OJ题目1198:a+b
- H.264中的NAL单元类型 nal_unit_type
- 题目1176:树查找 九度OJ
- nyoj 82 迷宫寻宝(一)BFS
- 等价二叉树
- POJ-2010-优先队列
- Lua闭包方式创建对象表。
- 堆排序解剖
- ALL in ALL
- 使用Java实现面向对象编程-->抽象和封装
- Mysql utf8 格式 升级为 utf8mb4
- LeetCode 234.Palindrome Linked List
- Lintcode 等价二叉树