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
Make Costs of Paths Equal in Binary Tree1522331Path 1:1+5+2 = 8Path 2:1+5+3 = 9Path 3:1+2+3 = 6Path 4:1+2+1 = 4Maximum path cost = 9Need increments: (9-8) + (9-9) + (9-6) + (9-4) = 1+0+3+5 = 9Optimal solution uses bottom-up balancing: 6 increments
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
Asked in
Meta 15 Amazon 12 Google 10 Microsoft 8
28.4K Views
Medium Frequency
~25 min Avg. Time
856 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