-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConstructBinaryTreeFromInorderAndPostorder.java
50 lines (40 loc) · 1.27 KB
/
ConstructBinaryTreeFromInorderAndPostorder.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
/* Tree node structure
class Node
{
int data;
Node left;
Node right;
Node(int value)
{
data = value;
left = null;
right = null;
}
}*/
class GfG
{
private static int findPosition(int[] in, int inorderStart, int inorderEnd, int element) {
for (int i = inorderStart; i <= inorderEnd; i++) {
if (in[i] == element) {
return i;
}
}
return -1;
}
private static Node solve(int[] in, int[] post, int[] postorderIndex, int inorderStart, int inorderEnd, int n) {
if (postorderIndex[0] < 0 || inorderStart > inorderEnd) {
return null;
}
int element = post[postorderIndex[0]--];
Node root = new Node(element);
int position = findPosition(in, inorderStart, inorderEnd, element);
root.right = solve(in, post, postorderIndex, position + 1, inorderEnd, n);
root.left = solve(in, post, postorderIndex, inorderStart, position - 1, n);
return root;
}
// Function to return a tree created from postorder and inorder traversals.
Node buildTree(int in[], int post[], int n) {
int[] postorderIndex = new int[]{n - 1};
return solve(in, post, postorderIndex, 0, n - 1, n);
}
}