From 3028c01721ef4a8ffb85c05848801535d3a9afc3 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 18 May 2024 23:19:35 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB979.=20Distribute=20Coins?= =?UTF-8?q?=20in=20Binary=20Tree=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/distribute-coins-in-binary-tree.java | 40 +++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 java/distribute-coins-in-binary-tree.java diff --git a/java/distribute-coins-in-binary-tree.java b/java/distribute-coins-in-binary-tree.java new file mode 100644 index 0000000..b7a67b8 --- /dev/null +++ b/java/distribute-coins-in-binary-tree.java @@ -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; + } +}