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.
我的代码:
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if( p == null && q == null){
return true;
}
else if(p == null && q != null){
return false;
}
else if(q == null && p != null){
return false;
}
else if( p.val == q.val){
if(isSameTree(p.left, q.left) == true && isSameTree(p.right, q.right) == true){
return true;
}
else{
return false;
}
}
else{
return false;
}
}
}
discuss中的更优解
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null) return true;
if(p == null || q == null) return false;<span style="white-space:pre"> </span>//此处合并了我第2、3个else if
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}