Print root to leaf path in BT
Pattern: Path sums
Walk the tree depth-first carrying the current path. At a leaf, save a copy of the path. After both children, remove the node from the path again so the next branch starts clean.
The problem
Return every path from the root to a leaf, as lists of values, from the leftmost leaf to the rightmost.
[1, 2, 3, null, 5] gives [[1, 2, 5], [1, 3]]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- When is a path complete?
- How can one list serve every path?
- Why copy the path when saving it?
Hints
Brute force, and why it fails
Rebuild each path from parent links after finding the leaves: O(n × h) too, but more code.
The key insight
Backtracking keeps one path list correct for every branch.
Dry run
| paths | [1, 2, 5] |
|---|
[1, 2, 3, null, 5]. Path [1], then [1, 2], then [1, 2, 5]: a leaf, save it.
Step 1 of 3
The plan
walk(n): if null: return
path.add(n.val)
if leaf: save copy of path
walk(left); walk(right)
path.remove last
Complexity
- Time
O(n × h)- Space
O(h)
Each saved path costs up to h to copy.
Edge cases
- Empty tree.
- One node.
- A long chain, where recursion is n deep.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<List<Integer>> allRootToLeaf(TreeNode root) {
List<List<Integer>> out = new ArrayList<>();
walk(root, new ArrayList<>(), out);
return out;
}
private void walk(TreeNode n, List<Integer> path, List<List<Integer>> out) {
if (n == null) return;
path.add(n.val); // step down
if (n.left == null && n.right == null) out.add(new ArrayList<>(path)); // a leaf: copy the path
walk(n.left, path, out);
walk(n.right, path, out);
path.remove(path.size() - 1); // step back up
}
}C++
class Solution {
public:
vector<vector<int>> allRootToLeaf(TreeNode* root) {
vector<vector<int>> out;
vector<int> path;
walk(root, path, out);
return out;
}
void walk(TreeNode* n, vector<int>& path, vector<vector<int>>& out) {
if (n == NULL) return;
path.push_back(n->val); // step down
if (n->left == NULL && n->right == NULL) out.push_back(path); // a leaf: copy the path
walk(n->left, path, out);
walk(n->right, path, out);
path.pop_back(); // step back up
}
};Python
class Solution:
def allRootToLeaf(self, root) -> list[list[int]]:
out, path = [], []
def walk(n):
if n:
path.append(n.val) # step down
if not n.left and not n.right:
out.append(list(path)) # a leaf: copy the path
walk(n.left)
walk(n.right)
path.pop() # step back up
walk(root)
return outCommon mistakes
- Saving the list itself instead of a copy.
- Forgetting to remove the node on the way back.