-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTreeReconstruct.java
48 lines (38 loc) · 1.33 KB
/
BinaryTreeReconstruct.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
public class BinaryTreeReconstruct {
class Node {
int data;
Node left, right;
Node(int item){
data = item;
left = right = null;
}
}
class Tree {
Node root;
int preOrderIndex = 0;
Node buildTree(int inOrder[], int preOrder[], int start, int end){
if (start > end)
return null;
//get the first element in pre order to know the root
Node tNode = new Node(preOrder[preOrderIndex++]);
//no more number between start and end ->
if (start == end){
return tNode;
}
//if there are some elements between start and end, recursive with those elements
int inOrderIndex = search(inOrder, start, end, tNode.data);
//reconstruct tree from those indexes
tNode.left = buildTree(inOrder, preOrder, start, inOrderIndex - 1);
tNode.right = buildTree(inOrder, preOrder, inOrderIndex + 1, end);
return tNode;
}
int search(int[] arr, int strt, int end, int value){
int i;
for (i = strt; i <= end; i++) {
if (arr[i] == value)
return i;
}
return i;
}
}
}