-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConstructBinaryTreefromInorderPreOrder.java
77 lines (49 loc) · 1.73 KB
/
ConstructBinaryTreefromInorderPreOrder.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/************************************************************
Following is the TreeNode class structure
class TreeNode<T>
{
public:
T data;
TreeNode<T> left;
TreeNode<T> right;
TreeNode(T data)
{
this.data = data;
left = null;
right = null;
}
};
************************************************************/
import java.util.*;
public class Solution
{
static int currIndex = 0;
public static TreeNode<Integer> buildBinaryTree(ArrayList<Integer> inorder, ArrayList<Integer> preorder)
{
currIndex = 0;
HashMap<Integer,Integer> inOrderMap = new HashMap<>();
populateHashMap(inOrderMap,inorder);
return buildTree(inOrderMap,preorder,0,inorder.size()-1);
}
public static void populateHashMap(HashMap<Integer,Integer> inOrderMap,ArrayList<Integer> inorder){
for(int i=0;i<inorder.size();i++){
inOrderMap.put(inorder.get(i),i);
}
}
public static TreeNode<Integer> buildTree(HashMap<Integer,Integer> inOrderMap,ArrayList<Integer> preorder,int start,int end){
if(currIndex>preorder.size()-1)
return null;
if(start>end){
return null;
}
int element = preorder.get(currIndex++);
TreeNode<Integer> node = new TreeNode<Integer>(element);
if(start==end){
return node;
}
int mid = inOrderMap.get(element);
node.left = buildTree(inOrderMap,preorder,start,mid-1);
node.right = buildTree(inOrderMap,preorder,mid+1,end);
return node;
}
}