Wrong Answer for Input {10,5,15}, {10,5,#,#,15} what does this input mean? The code seems right...


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

  • 1
    L

    Two things:

    1. Easy to overlook, but you have &&isSameTree(p.right, p.right) but you meant &&isSameTree(p.right, q.right);
    2. With this line return p.val==q.val && isSameTree(p.left,q.left) &&isSameTree(p.right,p.right) you are returning prematurely. You return if the first call to these is true, but want to continue the recursive calls in case that fails at some point. This should instead be
    public class Solution {
        public boolean isSameTree(TreeNode p, TreeNode q) {
            if(p == null && q == null){
                return true;
            }
            else if((p == null && q!=null) || (p != null && q == null)){
                return false;
            }
            else if (!isSameTree(p.left,q.left) || !isSameTree(p.right,q.right)) return false;
            return p.val==q.val;
            
        }
    }
    

    Also, you can simplify your second else if as shown above.


Log in to reply
 

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