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 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 + 1

Each 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
Base CampJunction AJunction BPeak 1Peak 2Peak 3+3 training stations+2 training stations๐Ÿ”๏ธ Trail Balancing Strategy1. Start from junctions near peaks2. Balance paths at each junction3. Add training stations to easier paths4. Work upward to base camp
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.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
34.2K Views
Medium Frequency
~18 min Avg. Time
1.4K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen