From 29f2194d56a7c531f808f390c8d025cf8921da15 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 23 Oct 2024 23:39:09 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB2641.=20Cousins=20in=20Bina?= =?UTF-8?q?ry=20Tree=20II=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/cousins-in-binary-tree-ii/ Signed-off-by: Matej Focko --- java/cousins-in-binary-tree-ii.java | 51 +++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 java/cousins-in-binary-tree-ii.java diff --git a/java/cousins-in-binary-tree-ii.java b/java/cousins-in-binary-tree-ii.java new file mode 100644 index 0000000..706e47c --- /dev/null +++ b/java/cousins-in-binary-tree-ii.java @@ -0,0 +1,51 @@ +class Solution { + private int get(TreeNode node) { + if (node == null) { + return 0; + } + return node.val; + } + + private void handleNode(Queue q, int siblings, TreeNode node) { + if (node == null) { + return; + } + + node.val = siblings; + q.offer(node); + } + + private int handleLevel(Queue q, int previous) { + int sum = 0; + + for (int i = q.size(); i > 0; --i) { + var node = q.poll(); + node.val = previous - node.val; + + var siblings = get(node.left) + get(node.right); + handleNode(q, siblings, node.left); + handleNode(q, siblings, node.right); + + sum += siblings; + } + + return sum; + } + + public TreeNode replaceValueInTree(TreeNode root) { + if (root == null) { + return root; + } + + Queue q = new ArrayDeque<>(); + + int sumAbove = root.val; + q.offer(root); + + while (!q.isEmpty()) { + sumAbove = handleLevel(q, sumAbove); + } + + return root; + } +}