Lightest Downward Path in a Level-Order Tree
Trees & GraphsAuto-graded · 20 test casesLast updated
Find the root-to-leaf path with the smallest value sum in a tree given as a level-order list, breaking ties toward the left, without recursion on 100,000-node skewed trees.
Lightest Downward Path
You are given a binary tree of integers encoded as a level-order list, and you must return the values on the root-to-leaf path whose values add up to the smallest total.
Input encoding
The list is in the style used by LeetCode:
tree[0]is the root. Remaining entries are read level by level, left to right.Nonemarks a child that does not exist. A missing node gets no slots for its own children, so the next entries in the list belong to the next existing nodes in the queue.- Trailing
Nonevalues may appear and should be ignored. - For example,
[5, 2, -3, 1, 4, None, 2]describes this tree:
5
/ \
2 -3
/ \ \
1 4 2
Task
A leaf is a node with no children. A root-to-leaf path starts at the root and ends at a leaf. Its sum is the total of all node values on the path.
Return the list of node values, from root to leaf, of the path with the smallest sum.
Tie-break rule
If several paths share the minimum sum, return the leftmost one. For two different tied paths, look at the first node where they diverge. The path that goes to the left child there is the leftmost. Depth does not matter: a deep leaf on the left beats a shallow leaf on the right.
Edge cases
- If
treeis empty, or its only entry isNone, return[]. - A single-node tree returns a list with just that value.
- Values can be negative, so a path cannot be abandoned early because its running sum looks large.
Constraints
- The number of actual nodes is between
0and100_000. -10^9 <= value <= 10^9for every node.- The tree can be extremely lopsided (for example, a chain of 100,000 nodes). Both building the tree and searching it must avoid deep recursion, since Python's default recursion limit is about 1,000.
Examples
Example 1
Input: lightest_leaf_path([5, 2, -3, 1, 4, None, 2])
Output: [5, -3, 2]
Example 2
Input: lightest_leaf_path([1, 2, 2])
Output: [1, 2]
Example 3
Input: lightest_leaf_path([0, -5, 4, None, None, -10, 6])
Output: [0, 4, -10]
Hints
Hint 1
Build the tree from the list with a queue, giving each real node its left and right child indexes. Do not recurse while building.
Hint 2
The sum for a root-to-leaf path is just the running total at the leaf. Compute each node's running total from its parent's total when you create it, and remember each node's parent.
Hint 3
Visit leaves in left-to-right order with an explicit stack (push right, then left) and replace the best leaf only on a strictly smaller sum. Rebuild the path once at the end by following parent links, instead of copying a path for every node.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
-
Build the tree iteratively. Walk the list with a queue of created nodes. For each node taken from the queue, the next two list entries are its left and right children (a
Nonemeans no child). Nodes are stored in parallel arrays: value, left index, right index, parent index, and running total. -
Running totals. When a child is created, its running total is its parent's total plus its own value. For a leaf, that total is the sum of its whole root-to-leaf path, so no path needs to be summed later.
-
Leftmost-first leaf scan. Use an explicit stack for a preorder DFS. Push the right child first and the left child second, so the left child is popped first. Leaves are therefore seen in left-to-right order. Keep the best leaf and replace it only when a leaf has a strictly smaller total.
-
Rebuild the path once. Follow parent links from the best leaf to the root, then reverse. This avoids copying a path for every node, which would cost O(n * h) on a chain.
Why it is correct
- By induction on depth, each node's running total equals the sum of values from the root to it. For leaves, this is exactly the path sum.
- Every root-to-leaf path ends at a unique leaf, and the DFS visits every leaf, so the minimum is taken over all paths. No pruning is done, which matters because negative values can lower a total later.
- Left-first preorder visits leaves in left-to-right order. Because replacement needs a strictly smaller sum, among tied leaves the first one visited is kept. That is the leftmost, meaning it goes left at the first point of divergence.
- Parent links give the exact root-to-leaf path in reverse.
Complexity
- Time: O(n) for building, scanning, and rebuilding.
- Space: O(n) for the arrays, queue, and stack.
Python integers do not overflow. Sums reach about 10^14, which would need a 64-bit type in other languages.
Reference solution
from typing import List, Optional
def lightest_leaf_path(tree: Optional[List[Optional[int]]]) -> List[int]:
if not tree or tree[0] is None:
return []
values = [tree[0]]
left = [-1]
right = [-1]
parent = [-1]
total = [tree[0]] # total[i] = sum of values from the root down to node i
queue = [0]
head = 0
pos = 1
n = len(tree)
while head < len(queue) and pos < n:
p = queue[head]
head += 1
for is_left in (True, False):
if pos < n and tree[pos] is not None:
c = len(values)
values.append(tree[pos])
left.append(-1)
right.append(-1)
parent.append(p)
total.append(total[p] + tree[pos])
if is_left:
left[p] = c
else:
right[p] = c
queue.append(c)
pos += 1
best_leaf = -1
best_sum = None
stack = [0]
while stack:
u = stack.pop()
lc, rc = left[u], right[u]
if lc == -1 and rc == -1:
if best_sum is None or total[u] < best_sum:
best_sum = total[u]
best_leaf = u
continue
if rc != -1:
stack.append(rc)
if lc != -1:
stack.append(lc)
path = []
u = best_leaf
while u != -1:
path.append(values[u])
u = parent[u]
path.reverse()
return path