You are given a perfect binary tree with n nodes, labeled from 1 to n in level-order. For any non-leaf node i, its left child is 2 * i and its right child is 2 * i + 1. Each node i has a positive integer cost cost[i - 1].
A root-to-leaf path cost is the sum of the costs of all nodes on that path.
In one operation, you may choose any node and increase its cost by 1.
Return the minimum number of operations needed so that every root-to-leaf path has the same total cost.
Constraints:
-
1 <= n <= 10^5
-
n
represents a perfect binary tree, so
n = 2^h - 1
for some integer
h >= 1
-
1 <= cost[i] <= 10^4
Example:
Input:
n = 7
cost = [1, 5, 2, 2, 3, 3, 1]
Tree:
1
/ \
5 2
/ \ / \
2 3 3 1
Output:
6
Explanation:
The root-to-leaf path sums are:
-
1 + 5 + 2 = 8
-
1 + 5 + 3 = 9
-
1 + 2 + 3 = 6
-
1 + 2 + 1 = 4
By incrementing selected node costs, all root-to-leaf path sums can be made equal using a minimum of 6 total increments.