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.
题意:判断两棵二叉树是否相同(结构相同、每个节点值相同)。
思路:
首先校验传入的参数,即判断传入的两个根节点与null的比较情况,如果都是null,相同返回true;一个是null一个不是,不同返回false。
如果两个根节点都不是null,两个节点值不同,返回false;值相同,需要继续判断他们的左子树和右子树是否都相同,这一步递归去判断就可以了。
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
if (p.val != q.val) {
return false;
}
boolean left = isSameTree(p.left, q.left);
boolean right = isSameTree(p.right, q.right);
return left && right;
}