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.
检查两颗二叉树是否一样,基本上都是一个套路,这里稍微不一样的就是递归到每一个节点都需要判断是否一样。
有一个节点不一样就可以判断不是一样的二叉树了。如果递归完了还是一样,那么就是一样的两颗二叉树了。这也是为什么判断变量isSame初始化为true了。
/**
* Definition for binary tree
* 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)
{
bool isSame = true;
HelperSame(p, q, isSame);
return isSame;
}
void HelperSame(TreeNode *p, TreeNode *q, bool &isSame)
{
if(!p && !q) return;
if (!p&&q || p&&!q)
{
isSame = false;
return;
}
if (q->val != p->val)
{
isSame = false;
return;
}
if (p && q)
HelperSame(p->left, q->left, isSame);
if (p && q)
HelperSame(p->right, q->right, isSame);
}
};
//2014-2-15 update
bool isSameTree(TreeNode *p, TreeNode *q)
{
if (!p && !q) return true;
if (!p && q || p && !q || p->val != q->val) return false;
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}