Problem
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Examples
Example 1:
graph TD; A[5] --> B[4] & C[8] B --> D[11] & E[null] C --> F[13] & G[4] D --> H[7] & I[2] G --> L[5] & M[1] style A fill:#f9f style B fill:#f9f style C fill:#f9f style D fill:#f9f style I fill:#f9f style G fill:#f9f style L fill:#f9f
|
|
Solution
Method 1 - Recursive DFS
This problem can be converted to be a typical depth-first search problem. A recursive depth-first search algorithm usually requires a recursive method call, a reference to the final result, a temporary result, etc.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
. - First, we think the time complexity isO(n)
because we only visit each node once. - But we forgot to calculate the cost to copy the current
path
when we found a valid path, which in the worst case can costO(n^2)
- 🧺 Space complexity:
O(h)
assuming recursive stack…in worst caseh = n
.