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.
Subscribe to see which companies asked this question.
这个问题首先思考如果两个树都是NULL,那么就return true,接下来如果有一颗是NULL另外一颗不是NULL,那么就返回false,这可以用一个if语句来表示。
if(p==NULL || q==NULL)
return p==q;
接下来来思考只有一个node的树,如果p和q都没有左右树,而且val一样,那么就返回true。
if(p->left==NULL && p->right==NULL && q->left==NULL && q->right==NULL && p->val==q->val)
return true;
然后如果两个val不一样,就返回false。
if(p->val!=q->val)
return false;
最后一种情况是q和p都有左子树或者右子树,那么就比较左子树和右子树是否相同,进入递归。
else
return (isSameTree(p->left,q->left))&&(isSameTree(p->right,q->right));
总的程序是:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
if(p==NULL || q==NULL)
return p==q;
if(p->left==NULL && p->right==NULL && q->left==NULL && q->right==NULL && p->val==q->val)
return true;
if(p->val!=q->val)
return false;
else
return (isSameTree(p->left,q->left))&&(isSameTree(p->right,q->right));
}
其实判断只有一个node的树是多余的步骤,因为如果删除那个判断步骤,两课树val一样的话,那么会判断两颗树的左子树和右子树,都是NULL,所以返还true。下面程序和上面程序一样的效果。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
if(p==NULL || q==NULL)
return p==q;
if(p->val!=q->val)
return false;
else
return (isSameTree(p->left,q->left))&&(isSameTree(p->right,q->right));
}