Easy, 5 Lines and Clean Java Solution


  • 18
    B

    You simply check if current node (starting with root) is a leaf node and sum is equal its value. If not, you just check left or right with the decremented sum. If one of them returns true, it has a path.

    public boolean hasPathSum(TreeNode root, int sum) {    
      if (root == null)
         return false;
            
      if (root.left == null && root.right == null && root.val == sum) // Leaf check
         return true;
            
      return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }

  • 0
    J

    Great solution!!!! thank you a lot!


  • 0
    B

    You're welcome :)


  • 0
    G

    Please Report this Solution..Guys


Log in to reply
 

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