forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCreate Binary Tree From Descriptions.java
41 lines (38 loc) · 1.19 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
class Solution {
public TreeNode createBinaryTree(int[][] descriptions) {
HashMap<Integer,TreeNode> map=new HashMap<>();
HashSet<Integer> children=new HashSet<>();
for(int[] info:descriptions)
{
int parent=info[0],child=info[1];
boolean isLeft=info[2]==1?true:false;
TreeNode parentNode=null;
TreeNode childNode=null;
if(map.containsKey(parent))
parentNode=map.get(parent);
else
parentNode=new TreeNode(parent);
if(map.containsKey(child))
childNode=map.get(child);
else
childNode=new TreeNode(child);
if(isLeft)
parentNode.left=childNode;
else
parentNode.right=childNode;
map.put(parent,parentNode);
map.put(child,childNode);
children.add(child);
}
TreeNode root=null;
for(int info[]:descriptions)
{
if(!children.contains(info[0]))
{
root=map.get(info[0]);
break;
}
}
return root;
}
}