mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
java: add «979. Distribute Coins in Binary Tree»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
04c2005f8a
commit
3028c01721
1 changed files with 40 additions and 0 deletions
40
java/distribute-coins-in-binary-tree.java
Normal file
40
java/distribute-coins-in-binary-tree.java
Normal file
|
@ -0,0 +1,40 @@
|
||||||
|
public class TreeNode {
|
||||||
|
int val;
|
||||||
|
TreeNode left;
|
||||||
|
TreeNode right;
|
||||||
|
|
||||||
|
TreeNode() {}
|
||||||
|
|
||||||
|
TreeNode(int val) {
|
||||||
|
this.val = val;
|
||||||
|
}
|
||||||
|
|
||||||
|
TreeNode(int val, TreeNode left, TreeNode right) {
|
||||||
|
this.val = val;
|
||||||
|
this.left = left;
|
||||||
|
this.right = right;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Solution {
|
||||||
|
private int distribute(TreeNode node) {
|
||||||
|
if (node == null) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int left = distribute(node.left);
|
||||||
|
int right = distribute(node.right);
|
||||||
|
|
||||||
|
moves += Math.abs(left) + Math.abs(right);
|
||||||
|
|
||||||
|
return node.val - 1 + left + right;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int moves;
|
||||||
|
|
||||||
|
public int distributeCoins(TreeNode root) {
|
||||||
|
moves = 0;
|
||||||
|
distribute(root);
|
||||||
|
return moves;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue