
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.
1from typing import List, Optional
2
3class TreeNode:
4 def __init__(self, val=0, left=None, right=None):
5 self.val = val
6 self.left = left
7 self.right = right
8
9class Solution:
10 def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
11 def dfs(node, current_sum, path):
12 if not node:
13 return
14 current_sum += node.val
15 path.append(node.val)
16 if not node.left and not node.right and current_sum == targetSum:
17 result.append(list(path))
18 else:
19 dfs(node.left, current_sum, path)
20 dfs(node.right, current_sum, path)
21 path.pop()
22
23 result = []
24 dfs(root, 0, [])
25 return resultIn this Python solution, we perform a DFS and track the path and its cumulative sum. Upon meeting both the leaf and sum conditions, we add the path to the result using list operations for copying and backtracking.
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 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.