Strange Behaviour - Giving wrong Answer.


  • 0
    R
    public class Solution {
      boolean bl = false , br = false , result = false;
        public boolean isSymmetric(TreeNode root) {
            
            //if root
            if(root == null)
              return true;
            
            result = Equals(root.left, root.right);
            return result;
        }
    
        public boolean Equals(TreeNode left, TreeNode right){
            boolean result = false;
            if(left == null && right == null) 
                return true;
    
            if(left != null && right != null){
    
                if(left.val == right.val)
                    {
                        bl = Equals(left.left, right.right);
                        br = Equals(left.right, right.left);
                        result = br&&bl ;                                //Issue.
    
                        //result = Equals(left.left, right.right) && Equals(left.right, right.left);
                    }
        
    
            return result;
        }
    }
    

    Hi Guys, in the function equals, I tried to seperately call Equals function on both left and right subtree after checking if their parent nodes are equal but it doesnt work.

      if(left.val == right.val)
     {
                        bl = Equals(left.left, right.right);
                        br = Equals(left.right, right.left);
                        result = br&&bl ;                               
     }
    

    Surprisingly, if I perform the same stuff using the below code it works .

    if(left.val == right.val)
                    {
                   result = Equals(left.left, right.right) && Equals(left.right, right.left);
                    }
    

    Please help me understand this behaviour.
    Thanks.


  • 0
    R

    This is unlikely, can you give the input on which you are seeing this behavior ? Also, you Equals method seems to be missing a return statement at the end of the method. This won't even compile.


Log in to reply
 

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