Home > OS >  Recursion does not work with one line solution
Recursion does not work with one line solution

Time:12-10

The question is about Leetcode 938.

My first solution is

return root == null ? 0 : root.val < low || root.val > high ? RangeSumBST(root.left, low, high)   RangeSumBST(root.right, low, high) : RangeSumBST(root.left, low, high)   RangeSumBST(root.right, low, high)   root.val;

And it is accepted.

Then I tried another one line solution for simplicity and readability

return root == null ? 0 : RangeSumBST(root.left, low, high)   RangeSumBST(root.right, low, high)   root.val < low || root.val > high ? 0 : root.val;

But it seems recursion doesn't work with the second solution. Only the most root value can be returned.

I would like to know what's the difference between these two solutions and why recursion does not work with the second solution.

CodePudding user response:

As the other's answers ,let make it more simpler.

//solution #1
return  (condition) ? 
( constant value )  //check condition T then constant value add 0 
 : 
( constant value)   root.val; //check condition F then constant value add root.val


//solution #2
return  (( constant value )   root.val ) < low|| root.val > high ?  
 0 // check new condition T then get only 0 
: 
root.val; // check new condition F then get only root.val 

as @Fildor's answer you should add the parenthesis

return root == null ? 0 : ( RangeSumBST(root.left, low, high)   RangeSumBST(root.right, low, high) )      ( (root.val < low || root.val > high) ? 0 : root.val );
  • Related