
Sponsored
Sponsored
Using a recursive DFS, traverse each path from root to leaf, maintaining the current path and its corresponding sum. When a leaf is reached, check if the path's sum matches the targetSum. Use backtracking to explore all paths.
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, due to the recursion stack.
1
In the JavaScript solution, a recursive helper function executes a DFS while tracking paths and current sums. When paths meet the target at leaf nodes, it appends the cloned array to the result list. Backtracking is performed by popping the last node in each path recursively.
An iterative approach using a stack can also be used for this problem. We maintain stacks that parallel traditional DFS traversal with added structures to track path and cumulative sum states for efficient exploration of all feasible root-to-leaf paths.
Time Complexity: O(N), as each node is processed exactly once.
Space Complexity: O(N), since results and stack can store all nodes during worst-case full-tree traversal.
1function TreeNode(val, left, right) {
2 this.val = (val===undefined ? 0 : val);
3 this.left = (left===undefined ? null : left);
4 this.right = (right===undefined ? null : right);
5}
6
7var pathSum = function(root, targetSum) {
8 if (!root) return [];
9 const result = [];
10 const stack = [[root, root.val, [root.val]]];
11 while (stack.length > 0) {
12 const [node, sum, path] = stack.pop();
13 if (node.left === null && node.right === null && sum === targetSum) {
14 result.push(path);
15 }
16 if (node.right) {
17 stack.push([node.right, sum + node.right.val, path.concat(node.right.val)]);
18 }
19 if (node.left) {
20 stack.push([node.left, sum + node.left.val, path.concat(node.left.val)]);
21 }
22 }
23 return result;
24};This JavaScript solution leverages a stack for iterative DFS traversal. Each stack element tracks the node, cumulative sum, and path. When paths qualify as solutions at leaf nodes, they're aggregated into results using path concatenation for subsequent level exploration.