Postorder returns one extendable branch to a parent while scoring a complete path through each node with both nonnegative child gains.
Problem trace
A winning path can use two branches; a returned path uses one
Read it this way:At value 10 with positive child gains 4 and 6, the local complete path scores 20. The upward return is 16, using only one child. Can the caller extend the twenty-point two-child path through another parent without revisiting this node?
Sources and provenance
Full interview answer 22 min read
Find the greatest sum of node values along any single connected path in a binary tree.
Problem
Input. The root of a finite integer-valued binary tree without cycles or shared children.
Output. Return the largest sum over all nonempty simple paths in the tree.
Rules. A path follows parent-child edges and cannot revisit a node or fork into three branches.
It may begin and end anywhere; it need not include the root or reach a leaf.
Negative values are allowed. Preserve the tree; the reference returns zero for an empty tree.
Example. Root -10 has children 9 and 20; node 20 has children 15 and 7.
Return 42 for the path 15 -> 20 -> 7.
A single node valued -3 returns -3, not zero.
Picture
In the right subtree, 15 -> 20 -> 7 sums to 42. Extending that fork to parent -10 would no longer be a path.
Node
Child gains used
Completed local score
Return upward
-4
0, 0
-4
-4
9
Clamp -4 to 0; other child 0
9
9
20
15, 7
42
35, through 15 only
-10
9, 35
34
25
Problem trace
Separate worked tree: score both branches but return only one
Input and goalFind the largest sum of any connected path in a binary tree.
Initialize at the root valueFor the shown tree, set global best = -10. Postorder must finish child gains before scoring each parent.
Score both branches at node 20Both child gains are positive, so the complete path through 20 scores 20 + 15 + 7 = 42; only the larger branch can continue upward, so return 35.
Return the global maximumThe completed path 15 -> 20 -> 7 has sum 42. It can use both branches because it ends locally rather than extending to a parent.
Use it when a connected tree path may bend once at a highest node, while any value returned to a parent must remain a single non-branching chain.
Keep true
After a node finishes, its return is the maximum sum of one downward branch starting there; global best is the maximum complete path in every finished subtree, and negative child returns contribute zero.
Reuse it
In tree DP, separate what a parent is allowed to extend from what may finish at the current node; clamp harmful optional branches, return the extendable shape, and update a global answer with the richer local shape.
For the shown tree, set global best = -10. Postorder must finish child gains before scoring each parent. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can 42 update the global best but not be returned as an extendable branch?
Reference drawing
Problem trace
A winning path can use two branches; a returned path uses one
Execution trace
Input and goalFind the largest sum of any connected path in a binary tree.
Initialize at the root valueFor the shown tree, set global best = -10. Postorder must finish child gains before scoring each parent.
Score both branches at node 20Both child gains are positive, so the complete path through 20 scores 20 + 15 + 7 = 42; only the larger branch can continue upward, so return 35.
Return the global maximumThe completed path 15 -> 20 -> 7 has sum 42. It can use both branches because it ends locally rather than extending to a parent.
Use it when a connected tree path may bend once at a highest node, while any value returned to a parent must remain a single non-branching chain.
Keep true
After a node finishes, its return is the maximum sum of one downward branch starting there; global best is the maximum complete path in every finished subtree, and negative child returns contribute zero.
Reuse it
In tree DP, separate what a parent is allowed to extend from what may finish at the current node; clamp harmful optional branches, return the extendable shape, and update a global answer with the richer local shape.
For the shown tree, set global best = -10. Postorder must finish child gains before scoring each parent. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can 42 update the global best but not be returned as an extendable branch?
Read it this way:At value 10 with positive child gains 4 and 6, the local complete path scores 20. The upward return is 16, using only one child. Can the caller extend the twenty-point two-child path through another parent without revisiting this node?
Code
Use this node type for a local run.
from dataclasses import dataclass@dataclassclass TreeNode: val: int left: "TreeNode | None" = None right: "TreeNode | None" = None
def max_path_sum(root: TreeNode | None) -> int: if root is None: return 0 best = root.val def one_branch(node: TreeNode | None) -> int: nonlocal best if node is None: return 0 left = max(0, one_branch(node.left)) right = max(0, one_branch(node.right)) best = max(best, node.val + left + right) return node.val + max(left, right) one_branch(root) return best
Export Only One Branch
one_branch(node) is the best downward path starting at that required node. It chooses at most one child.
A negative child contribution is optional and harmful, so clamp it to zero. Do not clamp the required current node.
best instead records completed paths. Score both nonnegative child gains there, but never return that two-branch sum to a parent.
Every simple tree path has one highest node. Scoring each such node covers every possible path without exporting a fork.
Keep All-Negative Answers Nonempty
Initialize best from root.val, not zero. A single node -3 must return -3, not an empty path’s score.
For the picture, global best stays 42 even though the root returns only 25. The exported root gain is not the answer.
Time is O(n) and recursive stack space O(h) for height h. Deep trees can exceed Python’s recursion limit.
The platform supplies TreeNode with val, left, and right; this snippet assumes that definition.
Recall: Why may local scoring use both children? That completed path will not gain a third branch from a parent.
Count Diameter Edges Instead
Choose this when: The objective is path length in edges, ignoring node values.
Return height in nodes. Two child heights then sum to the number of edges in a path through their parent.
def tree_diameter_edges(root): best = 0 def height(node): nonlocal best if node is None: return 0 left, right = height(node.left), height(node.right) best = max(best, left + right) return 1 + max(left, right) height(root) return best
A singleton has diameter zero regardless of its value. The pictured tree has diameter four edges, not weighted score 42.
Heights cannot be negative, so no gain clamp is needed. Time stays O(n) and recursive space O(h).
Evaluate Sum with Explicit Postorder
Choose this when: Python’s recursion depth prevents processing a skewed tree.
An enter frame schedules both children before a finish frame combines their results. The same one-branch contract still applies.
def max_path_sum_iterative(root): if root is None: return 0 gains, stack, best = {}, [(root, False)], root.val while stack: node, finished = stack.pop() if node is None: continue if not finished: stack.extend(((node, True), (node.right, False), (node.left, False))) continue left = max(0, gains.get(id(node.left), 0)) right = max(0, gains.get(id(node.right), 0)) best = max(best, node.val + left + right) gains[id(node)] = node.val + max(left, right) return best
Identity keys keep equal-valued or unhashable nodes separate. All children finish before their parent reads the saved gains.
The fixture still returns 42; a single -3 still returns -3. Empty input still returns zero.
Time remains O(n). Saved gains require O(n) storage plus an O(h) traversal stack; iteration is not automatically lower-memory.
Transfer
Choose the exported shape from what a parent may legally extend. The best completed object can require a richer local combination.