LeetCode——same tree 判断两棵树是否相同
题目描述:
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代码:
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if(p==NULL&&q==NULL)//都为空,返回true
return true;
else if(p==NULL&&q!=NULL)//其中一个为空,返回flase
return false;
else if(p!=NULL&&q==NULL)//其中一个为空,返回flase
return false;
else if(p->val!=q->val)//值不相同,返回false
return false;
else //左右子树都相同则返回true,否则返回false
return isSameTree(p->left,q->left)
&&isSameTree(p->right,q->right);
}
};