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.
采用先序遍历的思想,比较两个结点是否都是空来判断结构是否相同,以及它们的值是否相同,然后通过递归查看左右子树的情况
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if(p == NULL && q == NULL)return true;
if((p == NULL && q != NULL)||(p != NULL && q == NULL)||(p->val != q->val))return false;
bool left = isSameTree(p->left,q->left);
bool right = isSameTree(p->right,q->right);
return left&&right;
}
};
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null)return true;
if((p == null && q != null)||(p != null && q == null)||(p.val != q.val))return false;
boolean left = isSameTree(p.left,q.left);
boolean right = isSameTree(p.right,q.right);
return left&&right;
}
};