Given the
Output: ["1->2->5","1->3"]
Explanation: Leaf nodes are 5 and 3. The two root-to-leaf paths are 1→2→5 and 1→3.
Output: ["1"]
Explanation: There is only one node which is both root and leaf.
Constraints:
1 <= Number of nodes <= 100 -100 <= Node.val <= 100
Contents
Solution — DFS with Backtracking Complexity Analysis
We perform a depth-first traversal, building the current path string as we go. When we reach a leaf node (both children are null), we add the complete path to our result list. On the way back (backtracking), we simply do not append further — the string is passed by value so no explicit undo is needed.
Algorithm:
- Start DFS from the root with an empty path string.
- At each node, append the node's value (and
"->" if not a leaf) to the current path. - If the node is a leaf, add the current path to the result list.
- Recurse on the left and right children.
Trace through Example 1: root = [1,2,3,null,5]
| Node visited | Path so far | Action |
|---|---|---|
| 1 | "1->" | recurse left and right |
| 2 | "1->2->" | recurse left (null) and right (5) |
| 5 (leaf) | "1->2->5" | add to result |
| 3 (leaf) | "1->3" | add to result |
- Time: O(n) — every node is visited exactly once.
- Space: O(n) — recursion stack depth is O(h) where h is the tree height, and the string building is O(n) in the worst case (skewed tree path of length n).