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.
[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 backtrackto 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