-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCreate Binary Tree From Descriptions.java
42 lines (40 loc) · 1.4 KB
/
Create Binary Tree From Descriptions.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for a binary tree node.
* 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 {
public TreeNode createBinaryTree(int[][] descriptions) {
Map<Integer, TreeNode> mp = new HashMap<>();
Set<Integer> hasParent = new HashSet<>();
for (int i = 0; i < descriptions.length; i++) {
if (!mp.containsKey(descriptions[i][0]))
mp.put(descriptions[i][0], new TreeNode(descriptions[i][0]));
if (!mp.containsKey(descriptions[i][1]))
mp.put(descriptions[i][1], new TreeNode(descriptions[i][1]));
hasParent.add(descriptions[i][1]);
}
TreeNode root = null;
for (int i = 0; i < descriptions.length; i++) {
if (descriptions[i][2] == 1) { // left
mp.get(descriptions[i][0]).left = mp.get(descriptions[i][1]);
} else { // right
mp.get(descriptions[i][0]).right = mp.get(descriptions[i][1]);
}
if (!hasParent.contains(descriptions[i][0])) {
root = mp.get(descriptions[i][0]);
}
}
return root;
}
}