root = [5,4,8,1,2]
targetSum = 11TrueFollow child links from the root to a leaf. Return True if at least one complete path has values that add up to targetSum. A leaf has no children; stopping at an internal node does not count.
root = [5,4,8,1,2]
targetSum = 11TrueThe path 5 → 4 → 2 totals 11 and ends at a leaf.
root = [1,2]
targetSum = 1FalseThe root matches 1, but it is not a leaf. The only complete path totals 3.
root = [5,4,8,1,2] targetSum = 11 output: True
Each node is visited at most once. Finding a matching leaf can stop the search early.
Recursive calls use O(h) space, where h is the tree height: O(log n) for a balanced tree and O(n) for a skewed tree.
root = [5,4,8,1,2] targetSum = 11 output: True
Both approaches have the same worst-case bounds. Iterative DFS avoids Python's recursion limit. Negative values are allowed, so do not prune a path just because a partial total exceeds the target.
Each node is visited at most once. Finding a matching leaf can stop the search early.
The stack holds pending nodes along the DFS path: O(h) extra space, at most O(n).