STOP 11 · LISTS & TREES
Tree Paths and Recursive Aggregation
Return the one-sided gain, record the bent path globally O(n) time · O(h) stack
- Learn first
- Leads to
- How often asked
- asked by 5 companies · in 6 reportsMeta 2, Adobe 1, Capital One 1, Salesforce 1, TikTok / ByteDance 1
Warm up with this one
LC 112Path SumStuck? Peek at the approach
Subtract values along root-to-leaf paths, requiring the path to terminate at a leaf.
Key points
- The recursion returns the best one-sided downward path, because a path that continues upward can use only one child.
- The path that bends at the node (left + node + right) only updates the global answer; it is never returned to the parent.
- For root-to-leaf paths, add on entry and remove on exit; for path sums starting anywhere, use prefix sums with a hash map.
Common pitfalls
- Initialising the answer to 0 is wrong when every value in the tree is negative.
- Clamp a negative child gain to 0 (don't take that side), or it drags the answer down.
- Returning the bent path to the parent lets a path fork, which overcounts.
Watch it run
Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.
Tree traversal · stack and queue
Walk the tree in preorder, inorder, postorder, level order
Try your own input
- Order
- Preorder
- Output
- —
One tree, four traversal orders. #k under a node is its position in the current output.
InvariantThe three depth-first orders differ only in where the root is output: before, between or after its subtrees. Level order uses a queue, and first in, first out means level by level.
Template
Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 112, with it.
Python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val, self.left, self.right = val, left, right
def max_path_sum(root) -> int:
"""Largest sum of any non-empty path between two nodes."""
best = float("-inf")
def gain(node) -> int: # best downward path sum that starts at node
nonlocal best
if not node:
return 0
left, right = max(gain(node.left), 0), max(gain(node.right), 0)
best = max(best, node.val + left + right) # the path that bends at node
return node.val + max(left, right) # only one side can continue upward
gain(root)
return bestC++
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(v), left(l), right(r) {}
};
// Largest sum of any non-empty path between two nodes.
int maxPathSum(TreeNode* root) {
int best = INT_MIN;
function<int(TreeNode*)> gain = [&](TreeNode* node) { // best downward path from node
if (!node) return 0;
int left = max(gain(node->left), 0), right = max(gain(node->right), 0);
best = max(best, node->val + left + right); // the path that bends at node
return node->val + max(left, right); // only one side continues upward
};
gain(root);
return best;
}Java
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
private int best;
// Largest sum of any non-empty path between two nodes.
int maxPathSum(TreeNode root) {
best = Integer.MIN_VALUE;
gain(root);
return best;
}
private int gain(TreeNode node) { // best downward path sum that starts at node
if (node == null) return 0;
int left = Math.max(gain(node.left), 0), right = Math.max(gain(node.right), 0);
best = Math.max(best, node.val + left + right); // the path that bends at node
return node.val + Math.max(left, right); // only one side continues upward
}
}Go
import "math"
type TreeNode struct {
Val int
Left, Right *TreeNode
}
// maxPathSum returns the largest sum of any non-empty path between two nodes.
func maxPathSum(root *TreeNode) int {
best := math.MinInt
var gain func(*TreeNode) int // best downward path sum that starts at node
gain = func(node *TreeNode) int {
if node == nil {
return 0
}
left, right := max(gain(node.Left), 0), max(gain(node.Right), 0)
best = max(best, node.Val+left+right) // the path that bends at node
return node.Val + max(left, right) // only one side continues upward
}
gain(root)
return best
}Common variants
Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.
Prefix sums on a tree: undo the count on the way backO(n) time · O(h) space
To count downward paths that sum to target, starting anywhere: keep the root-to-node prefix sums in a hash map and look up pre - target, as in Subarray Sum Equals K; on leaving a node, remove its prefix so other branches never see it. LC 437 (Path Sum III).
Python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val, self.left, self.right = val, left, right
from collections import defaultdict
def path_sum_count(root, target: int) -> int:
"""Downward paths, starting and ending anywhere, whose values sum to target (LC 437)."""
seen = defaultdict(int) # prefix sums on the current root-to-node path
seen[0] = 1
count = 0
def dfs(node, pre: int) -> None:
nonlocal count
if not node:
return
pre += node.val
count += seen[pre - target] # a path ending here starts after an ancestor's prefix
seen[pre] += 1
dfs(node.left, pre)
dfs(node.right, pre)
seen[pre] -= 1 # leaving node: its prefix is off the path now
dfs(root, 0)
return countC++
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(v), left(l), right(r) {}
};
// Downward paths, starting and ending anywhere, whose values sum to target (LC 437).
int pathSumCount(TreeNode* root, long long target) {
unordered_map<long long, int> seen{{0, 1}}; // prefix sums on the current root-to-node path
int count = 0;
function<void(TreeNode*, long long)> dfs = [&](TreeNode* node, long long pre) {
if (!node) return;
pre += node->val;
if (auto it = seen.find(pre - target); it != seen.end()) count += it->second; // starts after an ancestor's prefix
seen[pre]++;
dfs(node->left, pre);
dfs(node->right, pre);
seen[pre]--; // leaving node: its prefix is off the path now
};
dfs(root, 0);
return count;
}Java
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
private final Map<Long, Integer> seen = new HashMap<>(); // prefix sums on the current root-to-node path
private int count;
// Downward paths, starting and ending anywhere, whose values sum to target (LC 437).
int pathSumCount(TreeNode root, long target) {
seen.clear();
seen.put(0L, 1);
count = 0;
dfs(root, 0, target);
return count;
}
private void dfs(TreeNode node, long pre, long target) {
if (node == null) return;
pre += node.val;
count += seen.getOrDefault(pre - target, 0); // a path ending here starts after an ancestor's prefix
seen.merge(pre, 1, Integer::sum);
dfs(node.left, pre, target);
dfs(node.right, pre, target);
seen.merge(pre, -1, Integer::sum); // leaving node: its prefix is off the path now
}
}Go
type TreeNode struct {
Val int
Left, Right *TreeNode
}
// pathSumCount counts downward paths, starting and ending anywhere, that sum to target (LC 437).
func pathSumCount(root *TreeNode, target int) int {
seen := map[int]int{0: 1} // prefix sums on the current root-to-node path
count := 0
var dfs func(node *TreeNode, pre int)
dfs = func(node *TreeNode, pre int) {
if node == nil {
return
}
pre += node.Val
count += seen[pre-target] // a path ending here starts after an ancestor's prefix
seen[pre]++
dfs(node.Left, pre)
dfs(node.Right, pre)
seen[pre]-- // leaving node: its prefix is off the path now
}
dfs(root, 0)
return count
}Lowest common ancestor: found on both sides means hereO(n) time · O(h) recursion depth
To find where two nodes meet: search both subtrees for p and q and hand either one upwards as soon as it is found; a node that receives results from both sides is the lowest common ancestor, and otherwise it passes on whichever side is non-empty. LC 236 (Lowest Common Ancestor of a Binary Tree); LC 1644 and LC 1650 are variations.
Python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val, self.left, self.right = val, left, right
def lowest_common_ancestor(root, p, q):
"""Deepest node with both p and q in its subtree, a node counting as its own descendant (LC 236)."""
if not root or root is p or root is q:
return root
left = lowest_common_ancestor(root.left, p, q)
right = lowest_common_ancestor(root.right, p, q)
if left and right: # p and q are on different sides: they meet here
return root
return left or rightC++
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(v), left(l), right(r) {}
};
// Deepest node with both p and q in its subtree, a node counting as its own descendant (LC 236).
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left && right) return root; // p and q are on different sides: they meet here
return left ? left : right;
}Java
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
// Deepest node with both p and q in its subtree, a node counting as its own descendant (LC 236).
TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) return root; // p and q are on different sides: they meet here
return left != null ? left : right;
}
}Go
type TreeNode struct {
Val int
Left, Right *TreeNode
}
// lowestCommonAncestor returns the deepest node with both p and q in its subtree (LC 236).
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil || root == p || root == q {
return root
}
left := lowestCommonAncestor(root.Left, p, q)
right := lowestCommonAncestor(root.Right, p, q)
if left != nil && right != nil { // p and q are on different sides: they meet here
return root
}
if left != nil {
return left
}
return right
}Why it works
- Every path has a unique highest node, the one closest to the root. Computing left + node + right with each node as that highest point covers every path, so the global maximum is right.
- What goes up to the parent can only be a one-sided chain, node + max(left, right, 0): a path that continues through the parent cannot also fork below, or it would not be a simple path.
- Clamping a negative gain to 0 means leaving that side out, since adding a negative chain only makes the path worse.
Say it in 30 seconds
When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.
树上最大路径和,我让递归函数返回从当前节点往下走的最大单侧链,负数当 0,不接。每条路径都有唯一的最高点,所以在每个节点把左链、自己、右链拼起来更新一次全局答案,就覆盖了所有路径。拐弯的路径只更新答案、不返回给父节点,因为经过父节点之后下面就不能再分叉。每个节点算一次,O(n)。For the maximum path sum, my recursion returns the best one-sided chain going down from the node, treating a negative chain as zero. Every path has a single highest node, so joining the left chain, the node and the right chain at every node and updating a global best covers all paths. The bent path only updates the answer and is never returned, because a path going up through the parent cannot fork below it. Each node is handled once, so it is O(n).Grade yourself
Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.
Quick quiz
3 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice
Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.
Template drills
Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.
These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.
class TreeNode:
def __init__(self, val=0, left=None, right=None): return bestPractice by stage
This stop's 13 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.
Foundation 2
| # | Problem | Approach | Rating |
|---|---|---|---|
| 112 | Path Sum | Subtract values along root-to-leaf paths, requiring the path to terminate at a leaf. | |
| 257 | Binary Tree Paths | Maintain a path to construct root-to-leaf strings, practicing state copying and backtracking. |
Core 5
| # | Problem | Approach | Rating |
|---|---|---|---|
| 113 | Path Sum II | Enumerate all root-to-leaf paths with the target sum and save independent path snapshots. | |
| 129 | Sum Root to Leaf Numbers | Pass the decimal prefix value downward and sum results at leaves. | |
| 1448 | Count Good Nodes in Binary Tree | Carry the path maximum to decide whether the current node satisfies the ancestor condition. | |
| 236 | Lowest Common Ancestor of a Binary Tree | Use results from the left and right subtrees to locate the lowest common ancestor of two nodes. | |
| 1650 | Lowest Common Ancestor of a Binary Tree III 🔒 | Use parent pointers to reduce lowest common ancestor to intersection of two ancestor chains. |
Advanced 6
| # | Problem | Approach | Rating |
|---|---|---|---|
| 437 | Path Sum III | Maintain path-prefix frequencies during tree DFS and undo changes when leaving a subtree. | |
| 124 | Binary Tree Maximum Path Sum | Find the maximum path sum by separating the contribution offered to a parent from the global best path. | |
| 1644 | Lowest Common Ancestor of a Binary Tree II 🔒 | When a target may be absent, verify its presence rather than immediately returning a candidate ancestor. | |
| 1123 | Lowest Common Ancestor of Deepest Leaves | Return subtree height and the deepest leaves' common ancestor together in one postorder traversal. | |
| 863 | All Nodes Distance K in Binary Tree | Treat parent-child links as undirected edges and run a fixed-distance BFS from the target. | |
| 1530 | Number of Good Leaf Nodes Pairs | Aggregate leaf-distance distributions upward and count valid leaf pairs across the left and right subtrees. |
OA questions on this topic 9
- Longest Path with Alternating Letters in TreeMicrosoft
- Longest Path With Different Adjacent CharactersMicrosoft
- Radio WavesSnowflake
- Largest Path Sum in Rooted Tree (Downward Only)Citadel
- Minimum Path Sum to Target in Binary TreeCitadel
- Get Minimum ServersCisco
- Disk Storage — palindromePaths on Rooted TreeUber
- Binary Tree: Subtree Sum, Maximum Path Sum, and Path NodesUber
- Graph Palindrome QueriesUber