Trees & BST · Pattern 2 of 12
Backtracking on trees: root-to-leaf paths and path sums
Add the node to a shared path, recurse into both children, then remove it on the way back. The path always holds exactly the nodes from the root to where you are.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Print or collect every root-to-leaf path
- Paths whose values add up to a target
- Paths that may start and end anywhere, as long as they go downward
The template
// Path Sum II: every root-to-leaf path that adds up to target
List<List<Integer>> pathSum(TreeNode root, int target) {
List<List<Integer>> res = new ArrayList<>();
dfs(root, target, new ArrayList<>(), res);
return res;
}
void dfs(TreeNode node, int remain, List<Integer> path, List<List<Integer>> res) {
if (node == null) return;
path.add(node.val); // choose
remain -= node.val;
if (node.left == null && node.right == null && remain == 0) res.add(new ArrayList<>(path)); // copy it
dfs(node.left, remain, path, res);
dfs(node.right, remain, path, res);
path.remove(path.size() - 1); // un-choose on the way back
}
// Path Sum III: downward paths with sum target, using prefix sums of the current path
int countPaths(TreeNode root, int target) {
Map<Long, Integer> seen = new HashMap<>();
seen.put(0L, 1); // the empty prefix
return count(root, 0, target, seen);
}
int count(TreeNode node, long sum, int target, Map<Long, Integer> seen) {
if (node == null) return 0;
sum += node.val;
int res = seen.getOrDefault(sum - target, 0); // paths that end at this node
seen.merge(sum, 1, Integer::sum);
res += count(node.left, sum, target, seen) + count(node.right, sum, target, seen);
seen.merge(sum, -1, Integer::sum); // undo before going back up
return res;
} # Path Sum II: every root-to-leaf path that adds up to target
def path_sum(root, target):
res, path = [], []
def dfs(node, remain):
if not node:
return
path.append(node.val) # choose
remain -= node.val
if not node.left and not node.right and remain == 0:
res.append(path[:]) # copy it
dfs(node.left, remain)
dfs(node.right, remain)
path.pop() # un-choose on the way back
dfs(root, target)
return res
# Path Sum III: downward paths with sum target, using prefix sums of the current path
def count_paths(root, target):
seen = {0: 1} # the empty prefix
def count(node, s):
if not node:
return 0
s += node.val
res = seen.get(s - target, 0) # paths that end at this node
seen[s] = seen.get(s, 0) + 1
res += count(node.left, s) + count(node.right, s)
seen[s] -= 1 # undo before going back up
return res
return count(root, 0) // Path Sum II: every root-to-leaf path that adds up to target
void dfs(TreeNode* node, int remain, vector<int>& path, vector<vector<int>>& res) {
if (!node) return;
path.push_back(node->val); // choose
remain -= node->val;
if (!node->left && !node->right && remain == 0) res.push_back(path); // copies it
dfs(node->left, remain, path, res);
dfs(node->right, remain, path, res);
path.pop_back(); // un-choose on the way back
}
vector<vector<int>> pathSum(TreeNode* root, int target) {
vector<vector<int>> res;
vector<int> path;
dfs(root, target, path, res);
return res;
}
// Path Sum III: downward paths with sum target, using prefix sums of the current path
int countFrom(TreeNode* node, long long sum, int target, unordered_map<long long, int>& seen) {
if (!node) return 0;
sum += node->val;
int res = seen.count(sum - target) ? seen[sum - target] : 0; // paths that end here
seen[sum]++;
res += countFrom(node->left, sum, target, seen) + countFrom(node->right, sum, target, seen);
seen[sum]--; // undo before going back up
return res;
}
int countPaths(TreeNode* root, int target) {
unordered_map<long long, int> seen{{0, 1}}; // the empty prefix
return countFrom(root, 0, target, seen);
} // Path Sum II: every root-to-leaf path that adds up to target
function pathSum(root, target) {
const res = [], path = [];
function dfs(node, remain) {
if (!node) return;
path.push(node.val); // choose
remain -= node.val;
if (!node.left && !node.right && remain === 0) res.push([...path]); // copy it
dfs(node.left, remain);
dfs(node.right, remain);
path.pop(); // un-choose on the way back
}
dfs(root, target);
return res;
}
// Path Sum III: downward paths with sum target, using prefix sums of the current path
function countPaths(root, target) {
const seen = new Map([[0, 1]]); // the empty prefix
function count(node, sum) {
if (!node) return 0;
sum += node.val;
let res = seen.get(sum - target) ?? 0; // paths that end at this node
seen.set(sum, (seen.get(sum) ?? 0) + 1);
res += count(node.left, sum) + count(node.right, sum);
seen.set(sum, seen.get(sum) - 1); // undo before going back up
return res;
}
return count(root, 0);
} The variations
-
1Collect every root-to-leaf path
Push the node, record the path at a leaf (if it matches), recurse, pop. The pop is what makes one shared list work for every path.
Now you solve- Path Sum II Medium Stuck? solution
-
2Prefix sums along the current path
A downward path from an ancestor to here has sum
prefix(here) - prefix(ancestor). Keep counts of the prefix sums on the current path in a map, exactly like subarray sum equals k, and undo them when you return.
Mistakes to avoid
- Adding
pathitself to the answer: it keeps changing. Add a copy. - Checking the target at a
nullchild instead of at a real leaf: a node with one child is not a leaf, and each leaf gets counted twice. - Path Sum III: forgetting to undo the prefix count, so sums from another branch leak into this one.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.