描述:
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.
思路:
由于这题标识为easy,判断两棵树是否相等,想到了用递归。有这几种可能,两棵树相等的充要条件为root的值相等&&左子树相等&&右子树相等,两棵树都为空时也相等,其中一棵为空时就不相等
代码:
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){val=x;}
}
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null&&q==null)//两棵树都为空时相等
return true;
if(p==null||q==null)//其中一棵为空时就不相等
return false;
//root的值相等&&左子树相等&&右子树相等
if(p.val==q.val&&isSameTree(p.left, q.left)&&isSameTree(p.right, q.right))
return true;
return false;
}