Highest-Sum Path in an Array-Backed Binary Tree
Hard · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
A rooted binary tree on n vertices (numbered 0 through n - 1) is encoded using two parallel arrays rather than object pointers:
values[i]holds the signed integer score assigned to vertexi.children[i]is a two-element list[left, right]giving the indices of vertexi's left and right children, with-1marking an absent child. (Any vertex index may serve as the root.)
A tree path is any non-empty simple walk of connected vertices following tree edges without repeating a vertex. A path may start and end anywhere in the tree — it is not required to include the root or reach a leaf, and it cannot split into three branches at a single vertex.
Implement max_path_sum(values, children) to compute the largest total score achievable over all valid tree paths. Because n can be as large as 200,000 even on a degenerate chain-shaped tree, your traversal must run iteratively without relying on deep call-stack recursion.
def max_path_sum(values: List[int], children: List[List[int]]) -> int:
Examples
Example 1
- Input:
values = [3, 8, 6],children = [[1, 2], [-1, -1], [-1, -1]] - Output:
17 - Explanation: Vertex
0(score3) connects leaf1(score8) and leaf2(score6). Walking1 -> 0 -> 2collects8 + 3 + 6 = 17.
Example 2
- Input:
values = [-3, 6, 5, -4, 8],children = [[1, 2], [-1, -1], [3, 4], [-1, -1], [-1, -1]] - Output:
16 - Explanation: Skipping the negative leaf
3(score-4) and traversing1 -> 0 -> 2 -> 4sums6 + (-3) + 5 + 8 = 16, beating2 -> 4(5 + 8 = 13) alone.
Example 3
- Input:
values = [-12, -4, -9, -15],children = [[1, 2], [-1, 3], [-1, -1], [-1, -1]] - Output:
-4 - Explanation: Every vertex carries a negative score, and a valid path must contain at least one vertex, so the single-vertex path
[1]achieves the best total-4.
Example 4
- Input:
values = [14],children = [[-1, -1]] - Output:
14 - Explanation: The lone vertex
0forms the only valid path, with total14.
Constraints
1 <= n <= 200,000, wheren == len(values) == len(children).-1,000 <= values[i] <= 1,000for every0 <= i < n.- Each
children[i]has length2, with entries in{-1} U {0, ..., n - 1}, and togetherchildrendescribes a single valid binary tree. - Solutions must avoid recursion-limit failures on trees of height up to
200,000.
Step-by-step walkthrough
Understand the array-based tree and path rules
Rather than
TreeNodeobject pointers, the binary tree is encoded in two parallel lists indexed0throughn - 1:values[i]holds the signed integer score of vertexi(-1,000to1,000).children[i] = [left_child, right_child], with-1marking a missing child.
For instance, Example 2 (
values = [-3, 6, 5, -4, 8]andchildren = [[1, 2], [-1, -1], [3, 4], [-1, -1], [-1, -1]]) encodes:node 0 (val -3) / \ node 1 (val 6) node 2 (val 5) / \ node 3 (val -4) node 4 (val 8)A valid tree path is any non-empty sequence of distinct adjacent vertices connected by tree edges. Three rules shape our approach right away:
- Paths need not include the root, and every path must contain at least one vertex (so on an all-negative tree such as
[-12, -4, -9, -15], the best total is-4, never0). ncan reach200,000, including a degenerate chain of height200,000. Python's default recursion limit (1,000) will raiseRecursionError, so we must manage our own heap-allocated stack in a loop.- Any index can be the root, so we identify the root as the vertex that never appears inside
children.
Why checking every pair of endpoints is too slow
Every pair of vertices
(u, v)in a tree defines one unique simple path. Testing alln * (n + 1) / 2endpoint pairs and walking upward to sum their weights examines roughly2 * 10^10pairs whenn = 200,000, and each walk takes up toO(n)steps on a chain. We need a bottom-up pass that evaluates all paths inO(n)total time.Key insight: group every path by its highest node
Every valid path in a rooted binary tree has a single vertex closest to the root — its highest point or "peak"
node. Starting fromnode, that path may descend into the left subtree, descend into the right subtree, descend into both subtrees (forming an arch), or consist ofnodealone.Notice that what
nodecan form as a complete arch peaking atnodediffers from whatnodecan extend upward to its parent:1) Path peaking at `node` (updates global answer): 2) Path handed up to `parent` (cannot fork!): [node] [parent] / \ | left chain right chain [node] (both sides allowed!) / \ pick ONE (cannot take both, or best side `node` would have 3 edges!)Define
downward_gain[node]as the best score of a non-empty path that starts atnodeand steps strictly downward:- Whenever a child's
downward_gainis negative, entering that subtree would lower our score, so we clamp each child's contribution at0:left_contrib = max(downward_gain[left_child], 0)(or0when absent). - Best arch peaking at
node:arch_sum = values[node] + left_contrib + right_contrib. - Best downward chain offered to
node's parent:downward_gain[node] = values[node] + max(left_contrib, right_contrib).
- Whenever a child's
Find the root and build a bottom-up order iteratively
Because
nodereadsdownward_gainfrom its children, children must be evaluated before their parents. Here is a concise iterative way to build that order:- Record every index referenced in
childreninsideis_child. Any index withis_child[node] == Falseis a root. - Traverse with an explicit list
stack: popnode, appendnodetoorder, and push its non--1children. Becausenodeentersorderbefore its children are popped, every parent precedes all of its descendants inorder. - Iterating over
reversed(order)therefore processes every child strictly before its parent!
Pop & append to `order`: 0 -> 2 -> 4 -> 3 -> 1 (every parent before its children) Read `reversed(order)`: 1 -> 3 -> 4 -> 2 -> 0 (every child before its parent!)def find_roots(children: List[List[int]]) -> List[int]: """Return every node index that never appears as another node's child.""" n = len(children) # is_child[i]: True if node i has a parent pointing to it. is_child = [False] * n for left_child, right_child in children: if left_child != -1: is_child[left_child] = True if right_child != -1: is_child[right_child] = True roots = [] for node in range(n): if not is_child[node]: roots.append(node) return roots def parents_first_order(children: List[List[int]]) -> List[int]: """Visit every node with an explicit stack so parents always appear before their children.""" # stack: node indices waiting to be expanded (lives on the heap, avoiding recursion limits). stack = find_roots(children) # order: node indices in parent-before-children order, e.g. [0, 2, 4, 3, 1]. order = [] while stack: node = stack.pop() order.append(node) for child in children[node]: if child != -1: stack.append(child) return order- Record every index referenced in
Compute downward gains and best arch sum
Now we sweep across
reversed(order)and evaluate both quantities at each vertex.Pay special attention to
best_sum = values[0]: initializing with an actual single-vertex path rather than0guarantees that when every weight in the tree is negative,best_sumfinishes as the least negative vertex score.def max_path_sum(values: List[int], children: List[List[int]]) -> int: n = len(values) # downward_gain[i]: best sum of a non-empty path starting at node i and going strictly downward. downward_gain = [0] * n # Initialize with a real single-node path so an all-negative tree never falsely returns 0. best_sum = values[0] # Reversing parent-before-children order guarantees both children are ready before their parent. order = parents_first_order(children) for node in reversed(order): left_child, right_child = children[node] # Clamp negative child gains to 0: if a subtree lowers the sum, we stop rather than enter it. left_contrib = 0 if left_child != -1: left_contrib = max(downward_gain[left_child], 0) right_contrib = 0 if right_child != -1: right_contrib = max(downward_gain[right_child], 0) # Arch path peaking at `node`: allowed to connect both the left and right downward chains. arch_sum = values[node] + left_contrib + right_contrib if arch_sum > best_sum: best_sum = arch_sum # A path extending upward to `node`'s parent cannot fork, so it picks at most one child side. downward_gain[node] = values[node] + max(left_contrib, right_contrib) return best_sumWalk through Example 2 step by step
Trace
values = [-3, 6, 5, -4, 8],children = [[1, 2], [-1, -1], [3, 4], [-1, -1], [-1, -1]].find_rootsreturns[0],parents_first_orderbuilds[0, 2, 4, 3, 1], andreversed(order)visits[1, 3, 4, 2, 0]starting frombest_sum = values[0] = -3:step node val left_contrib right_contrib arch_sum (val+L+R) downward_gain (val+max) best_sum 1 1 6 0 (leaf) 0 (leaf) 6 + 0 + 0 = 6 6 + 0 = 6 6 2 3 -4 0 (leaf) 0 (leaf) -4 + 0 + 0 = -4 -4 + 0 = -4 6 3 4 8 0 (leaf) 0 (leaf) 8 + 0 + 0 = 8 8 + 0 = 8 8 4 2 5 max(-4,0)=0 max(8,0)=8 5 + 0 + 8 = 13 5 + 8 = 13 13 5 0 -3 max(6,0)=6 max(13,0)=13 -3 + 6 + 13 = 16 -3 + 13 = 10 16Leaf
3(-4) is ignored because its downward gain clamps to0, whereas crossing root0(-3) connects1(6) with2 -> 4(13) for the winning total16.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def find_roots(children: List[List[int]]) -> List[int]: """Return every node index that never appears as another node's child.""" n = len(children) # is_child[i]: True if node i has a parent pointing to it. is_child = [False] * n for left_child, right_child in children: if left_child != -1: is_child[left_child] = True if right_child != -1: is_child[right_child] = True roots = [] for node in range(n): if not is_child[node]: roots.append(node) return roots def parents_first_order(children: List[List[int]]) -> List[int]: """Visit every node with an explicit stack so parents always appear before their children.""" # stack: node indices waiting to be expanded (lives on the heap, avoiding recursion limits). stack = find_roots(children) # order: node indices in parent-before-children order, e.g. [0, 2, 4, 3, 1]. order = [] while stack: node = stack.pop() order.append(node) for child in children[node]: if child != -1: stack.append(child) return order def max_path_sum(values: List[int], children: List[List[int]]) -> int: n = len(values) # downward_gain[i]: best sum of a non-empty path starting at node i and going strictly downward. downward_gain = [0] * n # Initialize with a real single-node path so an all-negative tree never falsely returns 0. best_sum = values[0] # Reversing parent-before-children order guarantees both children are ready before their parent. order = parents_first_order(children) for node in reversed(order): left_child, right_child = children[node] # Clamp negative child gains to 0: if a subtree lowers the sum, we stop rather than enter it. left_contrib = 0 if left_child != -1: left_contrib = max(downward_gain[left_child], 0) right_contrib = 0 if right_child != -1: right_contrib = max(downward_gain[right_child], 0) # Arch path peaking at `node`: allowed to connect both the left and right downward chains. arch_sum = values[node] + left_contrib + right_contrib if arch_sum > best_sum: best_sum = arch_sum # A path extending upward to `node`'s parent cannot fork, so it picks at most one child side. downward_gain[node] = values[node] + max(left_contrib, right_contrib) return best_sum✅ Submit now — all tests should pass.
Intuition & how it works
Picture a binary tree as hiking trails on a mountain with the root at the summit. Any simple trail without U-turns or three-way forks climbs to a single highest vertex (its peak) and optionally descends down the opposite branch. If we ask every vertex, "What is the highest-scoring trail whose peak is you?", the best answer across all vertices is guaranteed to be the overall maximum.
Checking all pairs of endpoints directly examines O(n^2) pairs and walks up to O(n) edges per pair (O(n^3) work), which is hopeless when n = 200,000. Even recursive tree dynamic programming — solving each subtree once and combining child answers at the parent — hits a wall in Python: recursion pushes pending calls onto the call stack (a fixed-depth memory region tracking active function invocations), which overflows on a 200,000-node chain.
To finish both children before their parent without recursion, we build a post-order sequence (every vertex appears after both of its subtrees). A clean two-step trick avoids complex state machines: run an iterative pre-order traversal (recording each parent before expanding its children) using a plain Python list as our stack, then iterate through that recorded list in reverse so every child is processed before its parent. At each vertex, negative child gains are clamped to 0 (meaning we stop rather than enter a score-lowering subtree), values[node] + left_contrib + right_contrib tests the arch peaking at node, and values[node] + max(left_contrib, right_contrib) stores the single-branch gain available to node's parent.
Trace values = [3, 8, 6] with children = [[1, 2], [-1, -1], [-1, -1]]:
1. Root 0 is popped first, followed by 2 and 1, producing order = [0, 2, 1] and reversed(order) = [1, 2, 0].
2. Leaf 1 (val = 8) and leaf 2 (val = 6) have no children: their downward_gain values are 8 and 6, raising best_sum to 8.
3. Root 0 (val = 3) combines left_contrib = 8 and right_contrib = 6: its arch score is 3 + 8 + 6 = 17, which wins as best_sum = 17.
Complexity
- Time:
O(n), wherenis the vertex count.find_rootsinspects thenchild pairs once,parents_first_orderpushes and pops each vertex once, and the reverse pass performsO(1)arithmetic at each vertex. - Space:
O(n)auxiliary space.is_child,order, anddownward_gaineach holdnentries, whilestackholds at mosth + 1indices (for tree heighth <= n), all stored safely on the heap rather than the C call stack.
Edge cases
- Single-vertex tree (
[14]or[-7]):orderhas one element, both child contributions are0, andbest_sumequalsvalues[0]. - All-negative weights (
[-12, -4, -9, -15]): every child contribution clamps to0, so each vertex is tested as a standalone 1-node path and-4wins becausebest_sumstarts atvalues[0]instead of0. - Crossing a negative bridge (
[-3, 6, 5, -4, 8]):6 + (-3) + 5 + 8 = 16beats5 + 8 = 13becausevalues[node]itself is never clamped when computingarch_sum. - Degenerate chain of
200,000vertices: heap-allocated lists handle depth200,000in milliseconds with zero recursion. - Root at an index other than
0:find_rootslocates whichever vertex has in-degree0rather than assuming vertex0is the root.
Common mistakes
- Passing
values[node] + left_contrib + right_contribupward to the parent: attaching a parent on top of both children givesnodedegree3(a Y-shaped fork, not a simple path). - Starting
best_sumat0: when every vertex score is negative,0represents an empty path, violating the non-empty path requirement. - Relying on recursion with
sys.setrecursionlimit:200,000Python frames consume tens of megabytes of native stack memory and can crash the interpreter. - Looping
for node in range(n - 1, -1, -1)directly: vertex labels are arbitrary, so a parent can have a higher index than its children. - Not clamping negative child gains at
0: forcing paths to extend all the way to leaves drags negative subtrees into positive paths.
Alternative approaches
- Single-stack
(node, expanded)post-order: push(root, False); upon popping(node, False), push(node, True)then its existing children withFalse; upon popping(node, True), both children are ready. This skips storing theorderarray, though reversing a pre-order list is simpler and faster in Python.
Follow-up questions
- How would you extend the algorithm to reconstruct the ordered sequence of node indices along an optimal path? Store a
next_down[node]array recording which child (left_child,right_child, or-1when neither child contributes positively) achieveddownward_gain[node]. Wheneverarch_sum > best_sum, recordbest_peak = node,left_head = left_child if left_contrib > 0 else -1, andright_head = right_child if right_contrib > 0 else -1. After the sweep, walknext_downfromleft_head, reverse that list, appendbest_peak, and walknext_downfromright_head— takingO(n)extra memory andO(path_length)time. - Suppose the tree were given as a
parentarray instead ofchildrenpairs — how would you locate the root and verify that the array encodes a valid binary tree? Check thatlen(parent) == n, every entry is-1or in0 .. n - 1, and exactly one index hasparent[i] == -1(that index is the root). Build achildrenlist by appending each nodeitoparent[i]'s child list while verifying no node receives more than two children. Finally, run the iterative stack traversal from the single root and verifylen(order) == n: reaching allnvertices acrossn - 1edges proves the graph is connected and acyclic. - How much auxiliary memory does the iterative traversal consume, and how could you reduce it when the binary tree is known to be height-balanced? The general algorithm allocates
O(n)auxiliary memory foris_child,order, anddownward_gain. When the tree is height-balanced, its heighthisO(log n)(~18 levels atn = 200,000), allowingO(log n)extra space: find the root inO(1)space by subtracting every non--1child index fromn * (n - 1) // 2, then run an(index, expanded)stack walk (or plain recursion, which is completely safe at depth ~18) keeping pending child gains on anO(h)stack instead of a length-narray.
Follow-up questions
- How would you extend the algorithm to reconstruct the ordered sequence of node indices along an optimal path?
- Suppose the tree were given as a `parent` array instead of `children` pairs — how would you locate the root and verify that the array encodes a valid binary tree?
- How much auxiliary memory does the iterative traversal consume, and how could you reduce it when the binary tree is known to be height-balanced?
Similar questions
- Division-Free Array Products Excluding Each Index
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One