Easy, 5 Lines and Clean Java Solution

  • 18

    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

    Great solution!!!! thank you a lot!

  • 0

    You're welcome :)

  • 0

    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.