#2673
Make Costs of Paths Equal in a Binary Tree
MediumApproaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | Unknown |
| Space | O(n) | Unknown |
💡
Intuition
Time UnknownSpace Unknown
Instead of calculating the cost for each path separately, we can directly find the maximum cost path and calculate the increments needed for all other paths to match this maximum. This reduces unnecessary calculations.
⚙️
Algorithm
3 steps- 1Step 1: Traverse the tree and calculate the cost of each path recursively, while keeping track of the maximum path cost.
- 2Step 2: For each leaf node, calculate the increments needed to match the maximum path cost.
- 3Step 3: Return the total increments.
solution.py37 lines
1class TreeNode:
2 def __init__(self, cost):
3 self.cost = cost
4 self.left = None
5 self.right = None
6
7def build_tree(cost):
8 nodes = [TreeNode(c) for c in cost]
9 for i in range(len(nodes)):
10 if 2 * i + 1 < len(nodes):
11 nodes[i].left = nodes[2 * i + 1]
12 if 2 * i + 2 < len(nodes):
13 nodes[i].right = nodes[2 * i + 2]
14 return nodes[0]
15
16def min_increments(n, cost):
17 root = build_tree(cost)
18 max_cost = 0
19 increments = 0
20
21 def dfs(node, current_cost):
22 nonlocal max_cost, increments
23 if not node:
24 return
25 current_cost += node.cost
26 if not node.left and not node.right:
27 increments += max_cost - current_cost
28 max_cost = max(max_cost, current_cost)
29 else:
30 dfs(node.left, current_cost)
31 dfs(node.right, current_cost)
32
33 dfs(root, 0)
34 return increments
35
36# Example usage
37print(min_increments(7, [1,5,2,2,3,3,1])) # Output: 6Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.