Tutorialspoint
Problem
Solution
Submissions

Path Sum II

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C program to find all root-to-leaf paths in a binary tree where each path's sum equals a given target sum. A leaf is a node with no children. Return all the valid paths as a list of lists, where each inner list represents one valid path from root to leaf.

Example 1
  • Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
  • Output: [[5,4,11,2],[5,8,4,5]]
  • Explanation:
    • Path 1: 5 -> 4 -> 11 -> 2, Sum = 5+4+11+2 = 22.
    • Path 2: 5 -> 8 -> 4 -> 5, Sum = 5+8+4+5 = 22.
    • Both paths sum to the target value 22.
    • These are the only two valid root-to-leaf paths.
Example 2
  • Input: root = [1,2,3], targetSum = 5
  • Output: []
  • Explanation:
    • Path 1: 1 -> 2, Sum = 1+2 = 3 (not equal to 5).
    • Path 2: 1 -> 3, Sum = 1+3 = 4 (not equal to 5).
    • No path sums to the target value 5.
    • Therefore, return empty result.
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^2) where n is number of nodes
  • Space Complexity: O(n) for recursion stack
ArraysAlgorithmsEYSamsung
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 depth-first search (DFS) to traverse all paths from root to leaves
  • Maintain a current path array to track the nodes in the current path
  • Keep track of the current sum as you traverse down the tree
  • When you reach a leaf node, check if the current sum equals target sum
  • If the sum matches, add a copy of the current path to the result
  • Use backtracking to remove the current node when returning from recursion

Steps to solve by this approach:

 Step 1: Define a tree node structure and initialize global variables for storing results.
 Step 2: Create a DFS helper function that takes current node, target sum, current path, and current sum.
 Step 3: Add the current node's value to the path and update the current sum.
 Step 4: Check if the current node is a leaf node (no left or right children).
 Step 5: If it's a leaf and current sum equals target sum, add the current path to results.
 Step 6: Recursively call DFS on left and right children to explore all paths.
 Step 7: Use backtracking principle - the path array naturally backtracks when recursion returns.

Submitted Code :