Skip to content

Commit def29e2

Browse files
committed
Add solution #979
1 parent 352d858 commit def29e2

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,061 LeetCode solutions in JavaScript
1+
# 1,062 LeetCode solutions in JavaScript
22

33
[https://leetcode.com/](https://leetcode.com/)
44

@@ -787,6 +787,7 @@
787787
976|[Largest Perimeter Triangle](./solutions/0976-largest-perimeter-triangle.js)|Easy|
788788
977|[Squares of a Sorted Array](./solutions/0977-squares-of-a-sorted-array.js)|Easy|
789789
978|[Longest Turbulent Subarray](./solutions/0978-longest-turbulent-subarray.js)|Medium|
790+
979|[Distribute Coins in Binary Tree](./solutions/0979-distribute-coins-in-binary-tree.js)|Medium|
790791
985|[Sum of Even Numbers After Queries](./solutions/0985-sum-of-even-numbers-after-queries.js)|Easy|
791792
989|[Add to Array-Form of Integer](./solutions/0989-add-to-array-form-of-integer.js)|Easy|
792793
994|[Rotting Oranges](./solutions/0994-rotting-oranges.js)|Medium|
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 979. Distribute Coins in Binary Tree
3+
* https://leetcode.com/problems/distribute-coins-in-binary-tree/
4+
* Difficulty: Medium
5+
*
6+
* You are given the root of a binary tree with n nodes where each node in the tree has node.val
7+
* coins. There are n coins in total throughout the whole tree.
8+
*
9+
* In one move, we may choose two adjacent nodes and move one coin from one node to another.
10+
* A move may be from parent to child, or from child to parent.
11+
*
12+
* Return the minimum number of moves required to make every node have exactly one coin.
13+
*/
14+
15+
/**
16+
* Definition for a binary tree node.
17+
* function TreeNode(val, left, right) {
18+
* this.val = (val===undefined ? 0 : val)
19+
* this.left = (left===undefined ? null : left)
20+
* this.right = (right===undefined ? null : right)
21+
* }
22+
*/
23+
/**
24+
* @param {TreeNode} root
25+
* @return {number}
26+
*/
27+
var distributeCoins = function(root) {
28+
let result = 0;
29+
traverse(root);
30+
return result;
31+
32+
function traverse(node) {
33+
if (!node) return 0;
34+
35+
const leftExcess = traverse(node.left);
36+
const rightExcess = traverse(node.right);
37+
const totalExcess = node.val + leftExcess + rightExcess - 1;
38+
39+
result += Math.abs(leftExcess) + Math.abs(rightExcess);
40+
41+
return totalExcess;
42+
}
43+
};

0 commit comments

Comments
 (0)