File tree 2 files changed +45
-1
lines changed
2 files changed +45
-1
lines changed Original file line number Diff line number Diff line change 1
- # 1,061 LeetCode solutions in JavaScript
1
+ # 1,062 LeetCode solutions in JavaScript
2
2
3
3
[ https://leetcode.com/ ] ( https://leetcode.com/ )
4
4
787
787
976|[ Largest Perimeter Triangle] ( ./solutions/0976-largest-perimeter-triangle.js ) |Easy|
788
788
977|[ Squares of a Sorted Array] ( ./solutions/0977-squares-of-a-sorted-array.js ) |Easy|
789
789
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|
790
791
985|[ Sum of Even Numbers After Queries] ( ./solutions/0985-sum-of-even-numbers-after-queries.js ) |Easy|
791
792
989|[ Add to Array-Form of Integer] ( ./solutions/0989-add-to-array-form-of-integer.js ) |Easy|
792
793
994|[ Rotting Oranges] ( ./solutions/0994-rotting-oranges.js ) |Medium|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments