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 vertex i.
  • children[i] is a two-element list [left, right] giving the indices of vertex i's left and right children, with -1 marking 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 (score 3) connects leaf 1 (score 8) and leaf 2 (score 6). Walking 1 -> 0 -> 2 collects 8 + 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 traversing 1 -> 0 -> 2 -> 4 sums 6 + (-3) + 5 + 8 = 16, beating 2 -> 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 0 forms the only valid path, with total 14.

Constraints

  • 1 <= n <= 200,000, where n == len(values) == len(children).
  • -1,000 <= values[i] <= 1,000 for every 0 <= i < n.
  • Each children[i] has length 2, with entries in {-1} U {0, ..., n - 1}, and together children describes a single valid binary tree.
  • Solutions must avoid recursion-limit failures on trees of height up to 200,000.

Step-by-step walkthrough

  1. Understand the array-based tree and path rules

    Rather than TreeNode object pointers, the binary tree is encoded in two parallel lists indexed 0 through n - 1:

    • values[i] holds the signed integer score of vertex i (-1,000 to 1,000).
    • children[i] = [left_child, right_child], with -1 marking a missing child.

    For instance, Example 2 (values = [-3, 6, 5, -4, 8] and children = [[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:

    1. 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, never 0).
    2. n can reach 200,000, including a degenerate chain of height 200,000. Python's default recursion limit (1,000) will raise RecursionError, so we must manage our own heap-allocated stack in a loop.
    3. Any index can be the root, so we identify the root as the vertex that never appears inside children.
  2. Why checking every pair of endpoints is too slow

    Every pair of vertices (u, v) in a tree defines one unique simple path. Testing all n * (n + 1) / 2 endpoint pairs and walking upward to sum their weights examines roughly 2 * 10^10 pairs when n = 200,000, and each walk takes up to O(n) steps on a chain. We need a bottom-up pass that evaluates all paths in O(n) total time.

  3. 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 from node, that path may descend into the left subtree, descend into the right subtree, descend into both subtrees (forming an arch), or consist of node alone.

    Notice that what node can form as a complete arch peaking at node differs from what node can 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 at node and steps strictly downward:

    • Whenever a child's downward_gain is negative, entering that subtree would lower our score, so we clamp each child's contribution at 0: left_contrib = max(downward_gain[left_child], 0) (or 0 when 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).
  4. Find the root and build a bottom-up order iteratively

    Because node reads downward_gain from its children, children must be evaluated before their parents. Here is a concise iterative way to build that order:

    1. Record every index referenced in children inside is_child. Any index with is_child[node] == False is a root.
    2. Traverse with an explicit list stack: pop node, append node to order, and push its non--1 children. Because node enters order before its children are popped, every parent precedes all of its descendants in order.
    3. 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
    
  5. 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 than 0 guarantees that when every weight in the tree is negative, best_sum finishes 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_sum
    
  6. Walk 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_roots returns [0], parents_first_order builds [0, 2, 4, 3, 1], and reversed(order) visits [1, 3, 4, 2, 0] starting from best_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            16
    

    Leaf 3 (-4) is ignored because its downward gain clamps to 0, whereas crossing root 0 (-3) connects 1 (6) with 2 -> 4 (13) for the winning total 16.

  7. 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), where n is the vertex count. find_roots inspects the n child pairs once, parents_first_order pushes and pops each vertex once, and the reverse pass performs O(1) arithmetic at each vertex.
  • Space: O(n) auxiliary space. is_child, order, and downward_gain each hold n entries, while stack holds at most h + 1 indices (for tree height h <= n), all stored safely on the heap rather than the C call stack.

Edge cases

  • Single-vertex tree ([14] or [-7]): order has one element, both child contributions are 0, and best_sum equals values[0].
  • All-negative weights ([-12, -4, -9, -15]): every child contribution clamps to 0, so each vertex is tested as a standalone 1-node path and -4 wins because best_sum starts at values[0] instead of 0.
  • Crossing a negative bridge ([-3, 6, 5, -4, 8]): 6 + (-3) + 5 + 8 = 16 beats 5 + 8 = 13 because values[node] itself is never clamped when computing arch_sum.
  • Degenerate chain of 200,000 vertices: heap-allocated lists handle depth 200,000 in milliseconds with zero recursion.
  • Root at an index other than 0: find_roots locates whichever vertex has in-degree 0 rather than assuming vertex 0 is the root.

Common mistakes

  • Passing values[node] + left_contrib + right_contrib upward to the parent: attaching a parent on top of both children gives node degree 3 (a Y-shaped fork, not a simple path).
  • Starting best_sum at 0: when every vertex score is negative, 0 represents an empty path, violating the non-empty path requirement.
  • Relying on recursion with sys.setrecursionlimit: 200,000 Python 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 with False; upon popping (node, True), both children are ready. This skips storing the order array, 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 -1 when neither child contributes positively) achieved downward_gain[node]. Whenever arch_sum > best_sum, record best_peak = node, left_head = left_child if left_contrib > 0 else -1, and right_head = right_child if right_contrib > 0 else -1. After the sweep, walk next_down from left_head, reverse that list, append best_peak, and walk next_down from right_head — taking O(n) extra memory and O(path_length) time.
  • 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? Check that len(parent) == n, every entry is -1 or in 0 .. n - 1, and exactly one index has parent[i] == -1 (that index is the root). Build a children list by appending each node i to parent[i]'s child list while verifying no node receives more than two children. Finally, run the iterative stack traversal from the single root and verify len(order) == n: reaching all n vertices across n - 1 edges 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 for is_child, order, and downward_gain. When the tree is height-balanced, its height h is O(log n) (~18 levels at n = 200,000), allowing O(log n) extra space: find the root in O(1) space by subtracting every non--1 child index from n * (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 an O(h) stack instead of a length-n array.

Follow-up questions

Similar questions

More Newrelic interview questions

All 2 Newrelic questions →