Class Solution
-
- All Implemented Interfaces:
public final class Solution2673 - Make Costs of Paths Equal in a Binary Tree.
Medium
You are given an integer
nrepresenting the number of nodes in a perfect binary tree consisting of nodes numbered from1ton. The root of the tree is node1and each nodeiin the tree has two children where the left child is the node2 * iand the right child is2 * i + 1.Each node in the tree also has a cost represented by a given 0-indexed integer array
costof sizenwherecost[i]is the cost of nodei + 1. You are allowed to increment the cost of any node by1any 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.
Example 1:
Input: n = 7, cost = 1,5,2,2,3,3,1
Output: 6
Explanation: We can do the following increments:
Increase the cost of node 4 one time.
Increase the cost of node 3 three times.
Increase the cost of node 7 two times.
Each path from the root to a leaf will have a total cost of 9.
The total increments we did is 1 + 3 + 2 = 6. It can be shown that this is the minimum answer we can achieve.
Example 2:
Input: n = 3, cost = 5,3,3
Output: 0
Explanation: The two paths already have equal total costs, so no increments are needed.
Constraints:
<code>3 <= n <= 10<sup>5</sup></code>
n + 1is a power of2cost.length == n<code>1 <= costi<= 10<sup>4</sup></code>
-
-
Constructor Summary
Constructors Constructor Description Solution()
-
Method Summary
Modifier and Type Method Description final IntegerminIncrements(Integer n, IntArray cost)-
-
Method Detail
-
minIncrements
final Integer minIncrements(Integer n, IntArray cost)
-
-
-
-