Skip to content

Commit 44ccb8b

Browse files
committed
tree from level order and in order
1 parent e17cb5a commit 44ccb8b

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package BinaryTree;
2+
3+
import javax.management.RuntimeMBeanException;
4+
5+
/**
6+
* Created by dheeraj on 7/9/2016.
7+
*/
8+
public class TreeFromInOrderLevelOrder {
9+
static int in[] = new int[]{4, 8, 10, 12, 14, 20, 22};
10+
static int level[] = new int[]{20, 8, 22, 4, 12, 10, 14};
11+
12+
static Node makeTree(int start, int end, int rootDataIndex) {
13+
if (start > end) {
14+
return null;
15+
}
16+
if (start == end) {
17+
return new Node(level[rootDataIndex]);
18+
}
19+
Node root = new Node(level[rootDataIndex]);
20+
int mid = -1;
21+
for (int x = start; x <= end; x++) {
22+
if (level[rootDataIndex] == in[x]) {
23+
mid = x;
24+
break;
25+
}
26+
}
27+
28+
int left = -1;
29+
//search first elment in level order which is
30+
// present in pre order,that level order lement is root
31+
for (int y = 0; y <= level.length - 1; y++) {
32+
for (int x = start; x <= mid - 1; x++) {
33+
if (level[y] == in[x]) {
34+
left = y;
35+
break;
36+
}
37+
}
38+
if (left != -1) {
39+
break;
40+
}
41+
}
42+
int right = -1;
43+
for (int y = 0; y <= level.length - 1; y++) {
44+
for (int x = mid + 1; x <= end; x++) {
45+
if (level[y] == in[x]) {
46+
right = y;
47+
break;
48+
}
49+
}
50+
if (right != -1) {
51+
break;
52+
}
53+
}
54+
if ((left != -1)) {
55+
root.left = makeTree(start, mid - 1, left);
56+
}
57+
if (right != -1) {
58+
root.right = makeTree(mid + 1, end, right);
59+
}
60+
return root;
61+
}
62+
63+
64+
public static void main(String[] strings) {
65+
Node node = makeTree(0, in.length - 1, 0);
66+
System.out.println();
67+
}
68+
}

0 commit comments

Comments
 (0)