KatInterview

Balance Root-to-Leaf Path Sums in Binary Tree

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsbinary-treegreedypost-order-traversal

Last updated

Tests bottom-up tree traversal with greedy balancing, recognizing that shared ancestors minimize total increments across multiple paths.

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 no node at that position).

A path is any sequence of nodes starting at the root and ending at a leaf. The sum of a path is the total of all node values along it.

You may increase any node's value by any non-negative integer. Your task is to make every root-to-leaf path have the same sum, using the minimum total amount of increments.

Write a function that returns this minimum total.

Constraints

  • The tree contains between 1 and 10⁴ nodes
  • Each node value is an integer in the range [0, 10⁶]
  • The input array uses level-order encoding with None for missing nodes
  • You must return the minimum total increment across all nodes

Examples

Example 1

Input: balance_tree_paths([1, 2, 3, 4, 5, 6, 7])

Output: 5

Example 2

Input: balance_tree_paths([5])

Output: 0

Example 3

Input: balance_tree_paths([1, 2, 3])

Output: 1

Example 4

Input: balance_tree_paths([1, 2, None, 3, None, 4, None, 5])

Output: 0

Hints

Hint 1

The final sum must be at least the current maximum path sum, since you can only increase values.

Hint 2

Process the tree from leaves upward; at each node, you want both subtrees to contribute the same path length before adding the node's own value.

Hint 3

When two subtrees have different maximum path sums, incrementing their common ancestor affects both subtrees at once, but incrementing the root of the smaller subtree is more efficient.