题目:
检查两棵二叉树是否等价。等价的意思是说,首先两棵二叉树必须拥有相同的结构,并且每个对应位置上的节点上的数都相等。
样例
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);
}
};
感想:
这个题还是较为容易的,只需要判读不是的情况即可,另外还要处理两个都是空的特殊情况。