java solution but why go wrong


  • 0
    Z

    public static boolean isSameTree(TreeNode p, TreeNode q) {
    if (p == null && q == null) return true;
    if((p==null&&q!=null)||(p!=null&&q==null))return false;
    boolean flag=false;
    if(p.val==q.val) flag=true;
    else{
    //why wrong when I write here "flag=false" replace "return flag"
    return flag;
    }
    flag=isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
    return flag;
    }


  • 0
    O

    if you write "flag = false", but does not return flag immediately, flag may become true later when program comes to excute

    flag=isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);

    Then you will return a wrong boolean value.


  • 0
    Z

    Thanks @ollie


Log in to reply
 

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