1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 01:36:57 +02:00
LeetCode/java/distribute-coins-in-binary-tree.java

41 lines
668 B
Java
Raw Normal View History

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;
}
}