Minimum-Length Root-to-Leaf Path with Target Sum
Trees & GraphsAuto-graded · 23 test casesLast updated
Tests tree traversal with state tracking to identify the shortest valid path satisfying a sum condition.
Problem Statement
You are given a binary tree represented as a level-order array where each element is either an integer (the node's value) or None (indicating a missing child). Your task is to find a root-to-leaf path whose node values sum to a given target integer K.
If multiple valid paths exist, return the one with the fewest nodes. If no valid path exists, return an empty list. When two or more paths tie for the shortest length, you may return any of them.
A leaf node is defined as a node with no children (both left and right children are absent).
Input Format
tree: A list representing the binary tree in level-order traversal.Nonevalues represent missing nodes.K: An integer representing the target sum.
Output Format
Return a list of integers representing the node values along the shortest valid root-to-leaf path. If no such path exists, return an empty list.
Constraints
- The tree contains at most 100,000 nodes.
- Tree height does not exceed 1,000.
- Node values can be negative, zero, or positive integers.
-10^9 ≤ node value ≤ 10^9-10^9 ≤ K ≤ 10^9
Notes
- The tree input uses level-order encoding: index 0 is the root, and for a node at index
i, its left child (if present) is at index2i+1and its right child at index2i+2.Noneentries represent gaps in the tree structure. - Only complete paths from root to leaf are valid; intermediate nodes that happen to sum to
Kdo not count. - Since node values can be negative, partial sums may exceed the target and later decrease back down.
Examples
Example 1
Input: min_length_target_sum_path([1, 2, 3, 4, 5, None, 6], 7)
Output: [1, 2, 4]
Example 2
Input: min_length_target_sum_path([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1], 22)
Output: [5, 4, 11, 2]
Example 3
Input: min_length_target_sum_path([1, 2, 3], 4)
Output: [1, 3]
Hints
Hint 1
Consider which traversal method naturally explores all root-to-leaf paths while tracking cumulative sums.
Hint 2
A leaf is only a node with both children missing—don't confuse internal nodes with leaves.
Hint 3
Since node values can be negative, you cannot prune based on the running sum exceeding the target.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that we must examine every root-to-leaf path in the tree, since node values can be negative and there is no way to prune branches early based on partial sums. We use depth-first search with an explicit stack to avoid recursion depth issues on tall trees.
The algorithm proceeds in two phases:
-
Build the tree structure. The input is a level-order array where
Nonemarks absent children. We construct a mapping from each node's array index to its left and right child indices using breadth-first traversal. This gives us O(1) child lookup during DFS. -
Explore all paths iteratively. Starting from the root, we maintain a stack of states, where each state contains:
- The current node's index
- The cumulative sum up to (but not including) this node
- The path taken to reach the parent of this node
When we reach a leaf (a node with both children absent), we check if the cumulative sum equals
K. If so, and if this path is shorter than the current best, we update our answer.
We push the right child before the left child onto the stack so that the left subtree is processed first when popping. This ensures deterministic tie-breaking among equal-length paths.
Why It Works
- Completeness: Every node is visited exactly once, and every leaf is reached via its unique path from the root.
- Correctness: A node qualifies as a leaf only when both children are missing. Internal nodes whose prefix sum equals
Kare correctly ignored. - Optimality: We update the best path only when a strictly shorter valid path is found. After visiting all leaves, the result is guaranteed to be minimal.
- Negative values: Since values can be negative, a running sum exceeding
Kmight decrease later, so we cannot terminate branches early based on sum alone.
Complexity
- Time: O(N · H), where N is the number of nodes and H is the tree height. Each node is visited once, but copying the path at each step costs O(H). Building the tree structure is O(N).
- Space: O(N + H²). The children lookup table takes O(N) space. The DFS stack depth is O(H), and each stack entry stores a path of length up to H.
For O(N) time, store parent pointers instead of copying paths at each step, then reconstruct the winning path at the end.
Solution Code
from typing import List, Optional
def min_length_target_sum_path(tree: List[Optional[int]], K: int) -> List[int]:
if not tree or tree[0] is None:
return []
# Parse the level-order array into a child-link structure
children = []
queue = [0]
next_idx = 1
head = 0
while head < len(queue) and next_idx < len(tree):
parent = queue[head]
head += 1
child_pair = []
for _ in range(2):
if next_idx < len(tree) and tree[next_idx] is not None:
child_pair.append(next_idx)
queue.append(next_idx)
else:
child_pair.append(None)
next_idx += 1
children.append((child_pair[0], child_pair[1]))
while len(children) < len(tree):
children.append((None, None))
# Iterative DFS to explore all root-to-leaf paths
shortest = None
stack = [(0, 0, [])]
while stack:
idx, cumulative, path_so_far = stack.pop()
val = tree[idx]
current_path = path_so_far + [val]
cumulative += val
left_child, right_child = children[idx]
if left_child is None and right_child is None:
# This is a leaf node
if cumulative == K and (shortest is None or len(current_path) < len(shortest)):
shortest = current_path
else:
# Internal node: push children onto stack
if right_child is not None:
stack.append((right_child, cumulative, current_path))
if left_child is not None:
stack.append((left_child, cumulative, current_path))
return shortest if shortest is not None else []