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
public static boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null){
return true;
}else if(p == null || q == null){//说明不可能都是null了
return false;
}else if(p.val != q.val){//经过上两个说明都不为空了
return false;
}
boolean isSameTreeLeft = isSameTree(p.left, q.left);
boolean isSameTreeRight = isSameTree(p.right, q.right);
return isSameTreeLeft && isSameTreeRight;
}
递归一定要找到合适的出口,只有p,q都不为空的时候再接着递归