Skip to content
mlmentorship

Binary Tree Maximum Path Sum

Return one extendable branch, score two branches locally, and keep nonempty path sums distinct from height or diameter.

Published · 22 min read ·Specialist ·Advanced

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Binary Tree Maximum Path Sum

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

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

Worked example: a winning path may branch, but the returned path may notAt value 10 with positive child gains 4 and 6, the local complete path scores 20. The upward return is 16, using only one child.A complete path can branch here; thereturned route cannot1046Complete path through both children:201046Choose one child for the routereturned to the caller16to parentExtendable path through one child: 16
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?
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.

NodeChild gains usedCompleted local scoreReturn upward
-40, 0-4-4
9Clamp -4 to 0; other child 099
2015, 74235, through 15 only
-109, 353425

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.
call rootreturn one branch; score two-10920-4157
Original node inventory
7091152203call root-10 root4-4 leaf5
callStackone_branch(-10)best-10nextdescend leftactiveStatecall roottopologyroot -> 9, root -> 20, 9 -> leaf, 20 -> 15, 20 -> 7
call root
4
call stack
one_branch(-10)
best
-10

Recognize it
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

Worked example: a winning path may branch, but the returned path may notAt value 10 with positive child gains 4 and 6, the local complete path scores 20. The upward return is 16, using only one child.A complete path can branch here; thereturned route cannot1046Complete path through both children:201046Choose one child for the routereturned to the caller16to parentExtendable path through one child: 16
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.
call rootreturn one branch; score two-10920-4157
Original node inventory
7091152203call root-10 root4-4 leaf5
callStackone_branch(-10)best-10nextdescend leftactiveStatecall roottopologyroot -> 9, root -> 20, 9 -> leaf, 20 -> 15, 20 -> 7
call root
4
call stack
one_branch(-10)
best
-10

Recognize it
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


@dataclass
class 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 and recursive stack space for height . 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 and recursive space .

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 . Saved gains require storage plus an 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.