-
Notifications
You must be signed in to change notification settings - Fork 161
/
distribute-coins-in-binary-tree.md
62 lines (44 loc) · 2.28 KB
/
distribute-coins-in-binary-tree.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<p>Given the <code>root</code> of a binary tree with <code>N</code> nodes, each <code>node</code> in the tree has <code>node.val</code> coins, and there are <code>N</code> coins total.</p>
<p>In one move, we may choose two adjacent nodes and move one coin from one node to another. (The move may be from parent to child, or from child to parent.)</p>
<p>Return the number of moves required to make every node have exactly one coin.</p>
<p> </p>
<div>
<p><strong>Example 1:</strong></p>
<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2019/01/18/tree1.png" style="width: 150px; height: 142px;" /></strong></p>
<pre>
<strong>Input: </strong><span id="example-input-1-1">[3,0,0]</span>
<strong>Output: </strong><span id="example-output-1">2</span>
<strong>Explanation: </strong>From the root of the tree, we move one coin to its left child, and one coin to its right child.
</pre>
<div>
<p><strong>Example 2:</strong></p>
<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2019/01/18/tree2.png" style="width: 150px; height: 142px;" /></strong></p>
<pre>
<strong>Input: </strong><span id="example-input-2-1">[0,3,0]</span>
<strong>Output: </strong><span id="example-output-2">3</span>
<strong>Explanation: </strong>From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.
</pre>
<div>
<p><strong>Example 3:</strong></p>
<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2019/01/18/tree3.png" style="width: 150px; height: 142px;" /></strong></p>
<pre>
<strong>Input: </strong><span id="example-input-3-1">[1,0,2]</span>
<strong>Output: </strong><span id="example-output-3">2</span>
</pre>
<div>
<p><strong>Example 4:</strong></p>
<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2019/01/18/tree4.png" style="width: 155px; height: 156px;" /></strong></p>
<pre>
<strong>Input: </strong><span id="example-input-4-1">[1,0,0,null,3]</span>
<strong>Output: </strong><span id="example-output-4">4</span>
</pre>
<p> </p>
<p><strong><span>Note:</span></strong></p>
<ol>
<li><code>1<= N <= 100</code></li>
<li><code>0 <= node.val <= N</code></li>
</ol>
</div>
</div>
</div>
</div>