Home > database >  why does the parentheses make a difference in this line of code
why does the parentheses make a difference in this line of code

Time:06-02

I was working on leetcode #112 and this is my solution:

    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null){
            return false;
        }
        return helper(root, targetSum);
    }
        private boolean helper(TreeNode root, int sum) {
            if(root.left == null && root.right == null) {
                return sum - root.val == 0;
            }
            
            return (root.left == null? false : helper(root.left, sum - root.val)) || 
                root.right == null? false : helper(root.right, sum - root.val);
        }
    
}

on the last return in the helper function, the test would only pass if there were parentheses around the ternary statements(shown around root.left). I was wondering why does the parenthese make a difference in this case?

CodePudding user response:

With parens, and boiling it down to bare essence, it's:

return (a ? false : b) || c ? false : d;

Without them, it's resolved as:

return a ? false : ((b || c) ? false : d);

CodePudding user response:

From the used operators the precedence is as follows:

  1. subtraction (left-to-right)
  2. equality (left-to-right)
  3. logical or (left-to-right)
  4. ternary operator (right-to-left)

where the upper ones overrule the lower

So suppose you have two ternary operators intertwined like so:

var value1 = a ? b : c || d ? e : f;
var value2 = (a ? b : c) || (d ? e : f);
var value3 = a ? b : (c || d) ? e : f;
var value4 = a ? b : ((c || d) ? e : f);

And value1 has no parenthesis, therefore we will compute the logical or first, such that we arrive at the equation for value3.

In value3 the next higher operator is the ternary operator, which is right-associative, such that we will compute it as if we would put the right-most ternary calculation in parenthesis as in equation for value4.

Now you should clearly see, that solution for value4 differs very much from the one for value2.

Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html https://introcs.cs.princeton.edu/java/11precedence/

  •  Tags:  
  • java
  • Related