0ms simple JAVA solution


  • 8
    V

    public class Solution {

    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) {
            boolean left = isSameTree(p.left, q.left);
            boolean right = isSameTree(p.right, q.right);
            return (left & right);
        }
    
        return false;
    }
    

    }


  • 1
    H
    public class Solution {
        public boolean isSameTree(TreeNode p, TreeNode q) {
            if(p!=null&&q!=null){
                return (p.val==q.val)&&isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
            }else if(p==null&&q==null){
                return true;
            }else{
                return false;
            }
        }
    }
    

    our code is almost the same ,it good to be good.


  • 0
    C

    The recursion part can still be improved as follows, so that when there is any left or right tree node not the same, the algorithm won't have to compare other nodes.

    if(p.val == q.val){
      boolean left = isSameTree(p.left, q.left);
    if(left == false){
      return false;
    }
    boolean right = isSameTree(p.right, q.right);
    if(right == false){
      return false;
    }
    return (left & right);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.