Maximum path sum between two leaves of a binary tree
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Google. It tests binary tree, dfs and dynamic programming.
You are given the root of a binary tree. Every node stores an integer, which may be negative. A leaf is a node with no children.
A leaf-to-leaf path starts at one leaf, moves along parent/child edges without visiting any node twice, and ends at a different leaf. Its sum is the total of the values of every node on it, including both leaves.
Implement max_leaf_to_leaf_sum(root) -> int | None that returns the largest such sum. If the tree has fewer than two leaves, return None.
Constraints
- 1 to 10^5 nodes.
- -10^9 <= node value <= 10^9 (sums can exceed 32-bit range).
- The tree can be very unbalanced, up to 10^5 levels deep.
Example 1
-50
/ \
4 1
/ \
8 7
The best path is 8 -> 4 -> 7 with sum 19. Paths through the root, such as 8 -> 4 -> -50 -> 1 = -37, are worse.
Example 2
0
/ \
-100 3
/
2
The node -100 has one child, so it is not a leaf and a path cannot stop there. The only leaf-to-leaf path is 2 -> -100 -> 0 -> 3, with sum -95.
Aim for O(n) time.
Clarifying questions
- If the root has only one child, can it be an end of the path? (Under this definition it is not a leaf.)
- Is a single-node tree one leaf, so the answer is
None? - Can values be very large or negative?
- Should we return the path too?
What a strong answer covers
- Does one post-order pass. For each node it returns the best sum of a downward path that ends at a leaf of its subtree, or "none".
- Updates the answer only at nodes with two children: left best + right best + node value.
- Passes a one-child node's value through without treating it as an endpoint.
- Uses an explicit stack, since the tree can be
10^5levels deep. That is O(n) time. - Tests both examples, all negative values, a chain with one leaf (answer
None), and a root with one child.
Follow-ups
- Return the nodes on the best path.
- Any node-to-node path.
- An n-ary tree.
- Count the leaf pairs that reach the best sum.
Where it's asked
What it tests
binary tree · dfs · dynamic programming
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
