From be27f896dcadb9275a3ee0f4f83b9594fc2331dc Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 15 Jul 2024 23:54:14 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB2196.=20Create=20Binary=20T?= =?UTF-8?q?ree=20From=20Descriptions=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- .../create-binary-tree-from-descriptions.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 java/create-binary-tree-from-descriptions.java diff --git a/java/create-binary-tree-from-descriptions.java b/java/create-binary-tree-from-descriptions.java new file mode 100644 index 0000000..79b0b2f --- /dev/null +++ b/java/create-binary-tree-from-descriptions.java @@ -0,0 +1,31 @@ +class Solution { + public TreeNode createBinaryTree(int[][] descriptions) { + Map nodes = new HashMap<>(); + + Set hasParent = new HashSet<>(); + for (int[] description : descriptions) { + int parent = description[0]; + int value = description[1]; + boolean isLeft = description[2] == 1; + + var parentNode = nodes.computeIfAbsent(parent, k -> new TreeNode(k)); + var node = nodes.computeIfAbsent(value, k -> new TreeNode(k)); + + if (isLeft) { + parentNode.left = node; + } else { + parentNode.right = node; + } + + hasParent.add(value); + } + + for (var node : nodes.values()) { + if (!hasParent.contains(node.val)) { + return node; + } + } + + return null; + } +}