forked from architsingla13/InterviewBit-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeFromPreAndInorder.java
More file actions
54 lines (39 loc) · 1.17 KB
/
BinaryTreeFromPreAndInorder.java
File metadata and controls
54 lines (39 loc) · 1.17 KB
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
package Trees;
import java.util.ArrayList;
/**
* Author - archit.s
* Date - 06/11/18
* Time - 11:06 PM
*/
public class BinaryTreeFromPreAndInorder {
class Index{
int index;
public Index(int idx){
this.index = idx;
}
}
public int search(ArrayList<Integer> A, int value, int start, int end){
for(int i=start;i<=end;i++){
if(A.get(i) == value){
return i;
}
}
return -1;
}
public TreeNode helper(ArrayList<Integer> preorder, ArrayList<Integer> inorder, Index idx,
int start, int end){
if(start > end){
return null;
}
TreeNode root = new TreeNode(preorder.get(idx.index));
int rootIndex = search(inorder,preorder.get(idx.index),start,end);
idx.index+=1;
root.left = helper(preorder,inorder,idx, start, rootIndex-1);
root.right = helper(preorder,inorder,idx, rootIndex+1, end);
return root;
}
public TreeNode buildTree(ArrayList<Integer> A, ArrayList<Integer> B) {
Index idx = new Index(0);
return helper(A,B,idx,0,A.size()-1);
}
}