java: add «2196. Create Binary Tree From Descriptions»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
a718efd3d8
commit
be27f896dc
1 changed files with 31 additions and 0 deletions
31
java/create-binary-tree-from-descriptions.java
Normal file
31
java/create-binary-tree-from-descriptions.java
Normal file
|
@ -0,0 +1,31 @@
|
|||
class Solution {
|
||||
public TreeNode createBinaryTree(int[][] descriptions) {
|
||||
Map<Integer, TreeNode> nodes = new HashMap<>();
|
||||
|
||||
Set<Integer> 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue