A Java Concise solution


  • 23
    M
    public boolean hasPathSum(TreeNode root, int sum) {
       if(root == null){
         return false;
       }
       if(root.left == null && root.right == null){
          return (root.val == sum);
       }
       return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
       	   
    }

  • 0
    C

    when you reach a leaf whose val is not equal to sum,then it would return false.But a tree may has another leaf that satisfies the condition.


  • 0
    T

    @Unlimited-Code It's a recursive call . It returns false if the curent node is NULL.
    Take this condition
    hasPathSum(root.left, sum - root.val) ,let's say left node is NULL and it returns false.
    Now the statement .
    return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    checks the right child by hasPathSum(root.right, sum - root.val);
    if the right child is also NULL then it is the case of reaching the leaf but the path sum to that leaf is not equal to the required sum.
    Only then it returns false thanks to ||(OR) operator.
    The best way to understand this kind of recursions is to Draw the tree and examine the code line by line.Will take couple of minutes,worth the effort.


  • 0
    C

    @theabhijitsarkar Thank you very much!!!
    I got it!!!


Log in to reply
 

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