题目:
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.
思路:要注意 return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);,而不是分开判断什么时候return isSameTree(p->left,q->left)和return isSameTree(p->right,q->right),因为这样需要考虑很多情况,很容易就漏情况了。
解答:/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL)
{
if(q!=NULL)
return 0;
else
return 1;
}
if(q==NULL)
{
if(p!=NULL)
return 0;
else
return 1;
}
if(p!=NULL&&q!=NULL)
{
if(p->val!=q->val)
return 0;
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}
}
};
这里贴出leetcode上的solution,用了最简洁的步骤
bool isSameTree(TreeNode *p,TreeNode *q){
if(p == NULL || q == NULL)
return (p==q);
return (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
}