VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-paths-root-specified-sum-binary-tree/

⇱ Paths from Root with a Sum in Binary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Paths from Root with a Sum in Binary tree

Last Updated : 9 May, 2026

Given a Binary tree and a sum, the task is to return all the paths, starting from root, that sums upto the given sum.
Note: This problem is different from root to leaf paths. Here path doesn't need to end on a leaf node.

Examples:

Input:

šŸ‘ 4

Output: [[1, 3, 4]]
Explanation: The below image shows the path starting from the root that sums upto the given sum

šŸ‘ 1


Input:

šŸ‘ 3

Output: [[10, 28], [10, 13, 15]]
Explanation: The below image shows the path starting from the root that sums upto the given sum

šŸ‘ 2

[Using DFS + Backtracking] - O(n²) Time and O(h) Space

We use DFS with backtracking to explore all root-to-node paths. While traversing, we maintain the current sum and path. Whenever the sum equals the target, we store that path. After exploring each node, we backtrack to explore other potential paths.

  • Start DFS traversal from root
  • Maintain a vector path and variable sum_so_far
  • Add current node value and If sum_so_far == target, store the current path
  • Recur for left and right subtrees.
  • Backtrack by removing last element from path

Output
1 3 4 
Comment
Article Tags:
Article Tags: