KatInterview

Lightest Downward Path in a Level-Order Tree

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsbinary-treedfsiterative-traversal

Last 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.
  • None marks 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 None values 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 tree is empty, or its only entry is None, 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 0 and 100_000.
  • -10^9 <= value <= 10^9 for 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.