Katkat

Return the Minimum-Sum Root-to-Leaf Path

MetaSoftware Engineer · Onsite

Last updated

Tests tree traversal, path reconstruction, tie-breaking logic, and handling deeply skewed trees with up to 100,000 nodes without exceeding recursion depth limits.

Problem Statement

Given the root of a binary tree where each node holds an integer value, return the values along the root-to-leaf path that yields the minimum total sum.

A root-to-leaf path starts at the root and ends at any leaf node (a node with no children). If multiple root-to-leaf paths have the exact same minimum sum, break ties deterministically by selecting the leftmost path (i.e., prioritize visiting left child branches before right child branches).

Your solution must handle trees with up to 100,000 nodes, including completely skewed trees (e.g., a linked list), without causing stack overflow errors.

Function Signature

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

def min_sum_path(root: Optional[TreeNode]) -> List[int]:
    pass

Examples

Example 1

       5
      / \
     2   -3
    / \    \
   1   4    2
  • Path 1: 5 -> 2 -> 1, sum = 8
  • Path 2: 5 -> 2 -> 4, sum = 11
  • Path 3: 5 -> -3 -> 2, sum = 4

Output: [5, -3, 2]
Explanation: The path 5 -> -3 -> 2 has the lowest sum (4).

Example 2

       1
      / \
     2   2
  • Path 1: 1 -> 2 (left leaf), sum = 3
  • Path 2: 1 -> 2 (right leaf), sum = 3

Output: [1, 2]
Explanation: Both paths have sum 3. By the tie-break rule, the leftmost path is chosen.

Constraints

  • The number of nodes in the tree is in the range [0, 100_000].
  • -10^9 <= Node.val <= 10^9
  • An empty tree (root = None) should return an empty list [].
  • The tree may be heavily skewed. Recursive solutions relying on the default Python recursion limit will fail.

Hints

Hint 1

A standard recursive DFS can trigger a stack overflow on a skewed tree with 100,000 nodes; consider an explicit stack (iterative DFS) or BFS.

Hint 2

Instead of copying the full path list at every step, track parent pointers or rebuild the path only after finding the target leaf.

Hint 3

Traverse left subtrees before right subtrees so that you only update your best path candidate when a strictly smaller sum is found.

Follow-up questions

  • How would you optimize memory to O(1) auxiliary space if parent pointers were already embedded in the TreeNode definition?
  • How does the problem change if the path can start and end at any arbitrary nodes, rather than strictly root-to-leaf?
  • If the tree is too large to fit in memory on a single machine, how would you design a distributed worker system to compute the minimum root-to-leaf path?