Create Binary Tree From Descriptions LeetCode solution in Java

1
class Solution {
2
public TreeNode createBinaryTree(int[][] descriptions) {
3
HashMap<Integer, TreeNode> map = new HashMap<>();
4
HashSet<Integer> children = new HashSet<>();
5
for (int[] info : descriptions) {
6
int parent = info[0], child = info[1];
7
boolean isLeft = info[2] == 1 ? true : false;
8
TreeNode parentNode = null;
9
TreeNode childNode = null;
10
if (map.containsKey(parent)) parentNode = map.get(parent);
11
else parentNode = new TreeNode(parent);
12
if (map.containsKey(child)) childNode = map.get(child);
13
else childNode = new TreeNode(child);
14
if (isLeft) parentNode.left = childNode;
15
else parentNode.right = childNode;
16
map.put(parent, parentNode);
17
map.put(child, childNode);
18
children.add(child);
19
}
20
TreeNode root = null;
21
for (int info[] : descriptions) {
22
if (!children.contains(info[0])) {
23
root = map.get(info[0]);
24
break;
25
}
26
}
27
return root;
28
}
29
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0