Make Costs of Paths Equal in a Binary Tree - Problem
Make Costs of Paths Equal in a Binary Tree
You're given a perfect binary tree with
โข Left child:
โข Right child:
Each node has an associated cost given by a 0-indexed array
๐ฏ Your Goal: Make all root-to-leaf path costs equal by incrementing any node's cost by 1 (as many times as needed).
๐ Return: The minimum number of increments needed.
Note: A perfect binary tree means every internal node has exactly 2 children, and all leaves are at the same level.
You're given a perfect binary tree with
n nodes numbered from 1 to n, where node 1 is the root. In this tree structure, each node i has:โข Left child:
2 * iโข Right child:
2 * i + 1Each node has an associated cost given by a 0-indexed array
cost where cost[i] represents the cost of node i + 1.๐ฏ Your Goal: Make all root-to-leaf path costs equal by incrementing any node's cost by 1 (as many times as needed).
๐ Return: The minimum number of increments needed.
Note: A perfect binary tree means every internal node has exactly 2 children, and all leaves are at the same level.
Input & Output
example_1.py โ Small Perfect Tree
$
Input:
n = 7, cost = [1,5,2,2,3,3,1]
โบ
Output:
6
๐ก Note:
Tree structure: 1(cost=1) -> 2(cost=5), 3(cost=2) -> leaves 4,5,6,7 with costs [2,3,3,1]. Path costs initially: 1+5+2=8, 1+5+3=9, 1+2+3=6, 1+2+1=4. Maximum is 9, so we need 1+3=4 increments to make all paths cost 9.
example_2.py โ Balanced Costs
$
Input:
n = 3, cost = [5,3,3]
โบ
Output:
0
๐ก Note:
Tree has root 1(cost=5) with leaves 2(cost=3) and 3(cost=3). Path costs: 5+3=8 and 5+3=8. Already equal, so 0 increments needed.
example_3.py โ Single Level Tree
$
Input:
n = 1, cost = [1]
โบ
Output:
0
๐ก Note:
Only one node (root), so only one path with cost 1. No increments needed.
Constraints
- 3 โค n โค 105
- n is odd (perfect binary tree property)
- 1 โค cost[i] โค 104
- cost.length == n
Visualization
Tap to expand
Understanding the Visualization
1
Identify Trail Junctions
Start from the junctions closest to the peaks (bottom-up)
2
Balance Each Junction
At each junction, make both paths equally difficult by adding training stations to the easier path
3
Propagate Upward
The balanced cost becomes the new cost for that junction
4
Continue to Base
Repeat until you reach the base camp (root)
Key Takeaway
๐ฏ Key Insight: The greedy bottom-up approach works because at each junction, matching the cheaper path to the expensive one minimizes total increments while ensuring all final paths are equal.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code