My accepted recursive solution in java

  • 1

    Using preorder traversal to judge if p equals q.

    public boolean isSameTree(TreeNode p, TreeNode q) {
            if((p==null && q!=null)||(p!=null && q==null)) return false;
            if(p==null && q==null) return true;
            if(p.val!=q.val) return false;
            boolean l=isSameTree(p.left,q.left);
            boolean r=isSameTree(p.right,q.right);
            if(l && r) return true;
            return false;

  • 4

    Your solution does more work than it needs to. If l is false, why even recurse into r?

Log in to reply

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