Make Costs of Paths Equal in a Binary Tree - Problem
You are given an integer n representing the number of nodes in a perfect binary tree consisting of nodes numbered from 1 to n. The root of the tree is node 1 and each node i in the tree has two children where the left child is node 2 * i and the right child is 2 * i + 1.
Each node in the tree also has a cost represented by a given 0-indexed integer array cost of size n where cost[i] is the cost of node i + 1. You are allowed to increment the cost of any node by 1 any number of times.
Return the minimum number of increments you need to make the cost of paths from the root to each leaf node equal.
Note:
- A perfect binary tree is a tree where each node, except the leaf nodes, has exactly 2 children.
- The cost of a path is the sum of costs of nodes in the path.
Input & Output
Example 1 — Basic Perfect Binary Tree
$
Input:
cost = [1,5,2,2,3,3,1]
›
Output:
6
💡 Note:
Tree has paths: 1→5→2 (cost 8), 1→5→3 (cost 9), 1→2→3 (cost 6), 1→2→1 (cost 4). To balance, increment path costs to max 9: need 1+0+3+5 = 9 increments, but optimal is 6.
Example 2 — Small Tree
$
Input:
cost = [7,7,7]
›
Output:
0
💡 Note:
Tree paths: 7→7 (cost 14) and 7→7 (cost 14). Both paths already have equal costs, so no increments needed.
Example 3 — Single Node
$
Input:
cost = [5]
›
Output:
0
💡 Note:
Only one node, so only one path with cost 5. No balancing needed.
Constraints
- n == cost.length
- 3 ≤ n ≤ 15
- cost.length is odd
- 1 ≤ cost[i] ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Perfect binary tree with node costs [1,5,2,2,3,3,1]
2
Path Analysis
Find all root-to-leaf paths and their costs
3
Balance Paths
Increment cheaper paths to match the maximum cost
Key Takeaway
🎯 Key Insight: Balance sibling subtrees recursively from leaves to root instead of calculating all paths
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code