Balance Root-to-Leaf Path Sums in Binary Tree
Trees & GraphsAuto-graded · 22 test casesLast 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
Nonefor 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is that incrementing an internal node raises every path passing through it simultaneously. This makes a bottom-up strategy optimal: process each node after its children are already balanced.
For each node, track the maximum path sum from that node down to any leaf in its subtree, after equalizing all paths within the subtree. Call this value max_path_from[node].
For a leaf: The only path is the node itself, so max_path_from = node.val with zero increments needed.
For a node with one child: No balancing is required. max_path_from = node.val + max_path_from[child].
For a node with two children: Both subtrees are already internally balanced at their respective maximum path sums. If these maxima differ, we must raise the shorter subtree. The most efficient way is to increment the root of the shorter subtree by exactly the difference |left_max - right_max|. This single increment lifts every path in that subtree at once. Then max_path_from = node.val + max(left_max, right_max).
Sum all the differences encountered during the traversal to get the total minimum increments.
Why It Works
Since we can only increase values, every final path sum must be at least the current maximum path sum across all root-to-leaf paths. We can achieve exactly this maximum by carefully placing increments, making it the optimal target.
When a subtree needs to be raised by some amount, placing that increment at the subtree's root is optimal because it affects all paths in the subtree with a single operation. Any other placement would require multiple increments totaling at least the same amount.
Processing bottom-up ensures that when we handle a node, both of its subtrees are already internally balanced, so we only need to reconcile the difference between them.
Complexity
Time: O(n) where n is the number of nodes. We build the tree structure in one pass and traverse it once in post-order.
Space: O(n) for the adjacency list and auxiliary arrays. The iterative approach avoids recursion depth issues with skewed trees that could exceed Python's default stack limit.
Solution
from typing import List, Optional
def balance_tree_paths(tree: List[Optional[int]]) -> int:
if not tree or tree[0] is None:
return 0
# Build adjacency list from level-order array
children = [[] for _ in tree]
traversal_order = [0]
next_idx = 1
queue_pos = 0
while queue_pos < len(traversal_order) and next_idx < len(tree):
parent_idx = traversal_order[queue_pos]
queue_pos += 1
for _ in range(2):
if next_idx >= len(tree):
break
if tree[next_idx] is not None:
children[parent_idx].append(next_idx)
traversal_order.append(next_idx)
next_idx += 1
# Post-order: compute maximum path sum from each node downward
max_path_from = [0] * len(tree)
total_increments = 0
for idx in reversed(traversal_order):
node_val = tree[idx]
child_list = children[idx]
if len(child_list) == 0:
max_path_from[idx] = node_val
elif len(child_list) == 1:
max_path_from[idx] = node_val + max_path_from[child_list[0]]
else:
left_max = max_path_from[child_list[0]]
right_max = max_path_from[child_list[1]]
total_increments += abs(left_max - right_max)
max_path_from[idx] = node_val + max(left_max, right_max)
return total_increments