题目:
Given 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.
比较两颗二叉树很简单,我的思路:先比较两棵树的比较节点的NULL情况,若两个都是NULL必然是true;一个是NULL,另一个不是则是false;两个都不是NULL则需要仔细考虑:
1 首先比较两棵树的比较节点,若两个节点的val不相同,则返回false,这里只能判断false,如果判断val相同,并不能肯定返回true,因为还要比较左右子节点。
2 然后比较两个节点的左右子节点,我这里用了一个&&,只有左右都相同才能返回true;
总结以上:只有一种情况为true;那就是两个都为NULL才能返回true,这其实就是比较两个叶子节点的值相同而已。然后依次递归回去,可以算是动态规划么。。。。(个人觉得也算得上吧)。代码如下:
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
//先检查是否为空
//都为空,返回true
if(p==NULL && q==NULL){
return true;
}
//两个都不为空,则分别检测左节点和右节点,只要有左右有一个为false,则为false,因此用&&
else if (p!=NULL && q!= NULL){
if(p->val != q->val){
return false;
}
return isSameTree(p->left , q->left) &&isSameTree( p->right , q->right);
}
//一个空,一个不空,返回false
else
return false;
}
};