EasyNeetCode150StringTreeDepth-First SearchBinary Tree
Binary Tree Paths
Return all root-to-leaf paths.
Examples
Input
root = [1,2,3,null,5]
Output
['1->2->5','1->3']
Two paths.
Constraints
- •
Number of nodes in [1,100] - •
-100 <= Node.val <= 100
Approaches
Recursively build paths.
CodeT: O(n^2) | S: O(n) stack depth + paths
Same approach.
CodeT: O(n^2) | S: O(n)
Join path string.
CodeT: O(n^2) | S: O(n)
Complexity Comparison
| Approach | Time | Space | Description |
|---|---|---|---|
| DFS | O(n^2) | O(n) stack depth + paths | Recursively build paths. |
| DFS Optimized | O(n^2) | O(n) | Same approach. |
| DFS with String Building | O(n^2) | O(n) | Join path string. |
DFS
T: O(n^2)S: O(n) stack depth + paths
Recursively build paths.
DFS Optimized
T: O(n^2)S: O(n)
Same approach.
DFS with String Building
T: O(n^2)S: O(n)
Join path string.
Common Mistakes
Not checking leaf node
Not handling single node
Path separator wrong