原题:
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.
解题:
递归判断每个位置的节点在树中的位置是否一致,再进一步判断对应的值是否相等。可以AC的C++代码如下:
bool isSameTree(TreeNode* p, TreeNode* q) {
if((!p && q) || (p && !q))
return false;
else if(!p && !q)
return true;
if(p->val != q->val)
return false;
else{
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
}