2673. Make Costs of Paths Equal in a Binary Tree
Tags:
Medium
Skills:
Tree
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Lưu ý: Perfect binary tree là trường hợp đặc biệt của full binary tree (mọi node có 0 hoặc 2 con), nhưng thêm điều kiện là các nút lá phải ở cùng một mức
Perfect binary tree
1 1
2 / \
3 2 3
4 / \ / \
5 4 5 6 7Full binary tree
1 1
2 / \
3 2 3
4 / \
5 4 5Approach
Chiến lược giải
Cụ thể
L = 2*i + 1 và R = 2*i + 2 (theo mảng 0-indexes)ans += abs(cost[L] - cost[R])cost[i] += max(cost[L], cost[R])Solution
1function minIncrements(n: number, cost: number[]): number {
2 let ans = 0;
3 for(let i = Math.floor(n / 2) - 1;i >=0;--i) {
4 const L = i * 2 + 1;
5 const R = i * 2 + 2;
6 ans += Math.abs(cost[L] - cost[R]);
7 cost[i] += Math.max(cost[L], cost[R]);
8 }
9 return ans
10};