Tutorialspoint
Problem
Solution
Submissions

Path Sum in Binary Tree

Certification: Basic Level Accuracy: 0% Submissions: 1 Points: 8

Write a Java program to determine if the binary tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Example 1
  • Input:
    • root = [5,4,8,11,null,13,4,7,2,null,null,null,1]
    • targetSum = 22
  • Output: true
  • Explanation:

    Path Sum Binary Tree With Sum 22

    • There exists a root-to-leaf path 5 -> 4 -> 11 -> 2 with a sum of 22.
Example 2
  • Input:
    • root = [1,2,3]
    • targetSum = 5
  • Output: false
  • Explanation:

    Path Sum Binary Tree With Sum 5

    • There does not exist a path that sums to 5.
Constraints
  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 ≤ Node.val ≤ 1000
  • -1000 ≤ targetSum ≤ 1000
  • Time Complexity: O(n), where n is the number of nodes in the tree.
  • Space Complexity: O(h), where h is the height of the tree.
Binary TreeKPMGSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a recursive approach to traverse all root-to-leaf paths.
  • At each node, subtract the node's value from the target sum.
  • When reaching a leaf node, check if the remaining sum equals the leaf's value.
  • A leaf node is one with no children.
  • The path must end at a leaf node to be considered valid.

Steps to solve by this approach:

 Step 1: Check if the tree is empty (root is null). If so, return false.
 Step 2: Check if the current node is a leaf node (no left or right children).
 Step 3: If it's a leaf node, check if its value equals the target sum.
 Step 4: If not a leaf node, subtract the current node's value from the target sum.
 Step 5: Recursively check if either the left or right subtree has a path with the remaining sum.
 Step 6: Return true if any path is found that satisfies the condition.
 Step 7: Return false if no valid path exists.

Submitted Code :