Tutorialspoint
Problem
Solution
Submissions

Path Sum

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Given the root of a binary tree and an integer targetSum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children.

Example 1
  • Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
  • Output: true
  • Explanation:
     Step 1: Start from the root (5)
     Step 2: Follow the path: 5 -> 4 -> 11 -> 2
     Step 3: Sum the values: 5 + 4 + 11 + 2 = 22 Step 4: Since the sum equals the target and the path ends at a leaf node, return true
Example 2
  • Input: root = [1,2,3], targetSum = 5
  • Output: false
  • Explanation:
     Step 1: Start from the root (1)
     Step 2: Follow path 1: 1 -> 2 = 3 (not equal to targetSum)
     Step 3: Follow path 2: 1 -> 3 = 4 (not equal to targetSum)
     Step 4: No root-to-leaf path sums to 5, so return false
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
  • Space Complexity: O(h) where h is the height of the tree
TreeHCL TechnologiesLTIMindtree
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 depth-first search approach
  • At each node, subtract its value from the target sum
  • If you reach a leaf node and the remaining sum equals the node's value, return true
  • If you reach a leaf node and the remaining sum doesn't equal the node's value, return false
  • For non-leaf nodes, recursively check both left and right subtrees

Steps to solve by this approach:

 Step 1: Check if the root is NULL. If so, return false as an empty tree has no paths.

 Step 2: Subtract the current node's value from the target sum.
 Step 3: Check if the current node is a leaf (no left or right children).
 Step 4: If it's a leaf and the remaining target sum is 0, we've found a valid path, so return true.
 Step 5: If it's not a leaf, recursively check both left and right subtrees with the updated target sum.
 Step 6: Return true if either the left or right subtree contains a valid path, otherwise return false.
 Step 7: The recursion will naturally backtrack, effectively "adding back" node values as it returns from deeper levels.

Submitted Code :