KatInterview

Minimum-Length Root-to-Leaf Path with Target Sum

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphsbinary-treedfspath-finding

Last 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. None values 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 index 2i+1 and its right child at index 2i+2. None entries represent gaps in the tree structure.
  • Only complete paths from root to leaf are valid; intermediate nodes that happen to sum to K do 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.