Skip to content

Commit d2f8a10

Browse files
authored
Merge pull request #438 from prtk418/prtk418_binary_tree_construction_from_inorder_and_postorder_in_java
construct BST from inorder and postorder in java
2 parents d3f2c83 + 003a402 commit d2f8a10

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
class Node
2+
{
3+
int data;
4+
Node left, right;
5+
6+
public Node(int data)
7+
{
8+
this.data = data;
9+
left = right = null;
10+
}
11+
}
12+
13+
// Class Index created to implement pass by reference of Index
14+
class Index
15+
{
16+
int index;
17+
}
18+
19+
class BinaryTree
20+
{
21+
/* Recursive function to construct binary of size n
22+
from Inorder traversal in[] and Preorder traversal
23+
post[]. Initial values of inStrt and inEnd should
24+
be 0 and n -1. The function doesn't do any error
25+
checking for cases where inorder and postorder
26+
do not form a tree */
27+
Node buildUtil(int in[], int post[], int inStrt,
28+
int inEnd, Index pIndex)
29+
{
30+
// Base case
31+
if (inStrt > inEnd)
32+
return null;
33+
34+
/* Pick current node from Preorder traversal using
35+
postIndex and decrement postIndex */
36+
Node node = new Node(post[pIndex.index]);
37+
(pIndex.index)--;
38+
39+
/* If this node has no children then return */
40+
if (inStrt == inEnd)
41+
return node;
42+
43+
/* Else find the index of this node in Inorder
44+
traversal */
45+
int iIndex = search(in, inStrt, inEnd, node.data);
46+
47+
/* Using index in Inorder traversal, construct left and
48+
right subtress */
49+
node.right = buildUtil(in, post, iIndex + 1, inEnd, pIndex);
50+
node.left = buildUtil(in, post, inStrt, iIndex - 1, pIndex);
51+
52+
return node;
53+
}
54+
55+
// This function mainly initializes index of root
56+
// and calls buildUtil()
57+
Node buildTree(int in[], int post[], int n)
58+
{
59+
Index pIndex = new Index();
60+
pIndex.index = n - 1;
61+
return buildUtil(in, post, 0, n - 1, pIndex);
62+
}
63+
64+
/* Function to find index of value in arr[start...end]
65+
The function assumes that value is postsent in in[] */
66+
int search(int arr[], int strt, int end, int value)
67+
{
68+
int i;
69+
for (i = strt; i <= end; i++)
70+
{
71+
if (arr[i] == value)
72+
break;
73+
}
74+
return i;
75+
}
76+
77+
/* This funtcion is here just to test */
78+
void preOrder(Node node)
79+
{
80+
if (node == null)
81+
return;
82+
System.out.print(node.data + " ");
83+
preOrder(node.left);
84+
preOrder(node.right);
85+
}
86+
87+
public static void main(String[] args)
88+
{
89+
BinaryTree tree = new BinaryTree();
90+
int in[] = new int[]{4, 8, 2, 5, 1, 6, 3, 7};
91+
int post[] = new int[]{8, 4, 5, 2, 6, 7, 3, 1};
92+
int n = in.length;
93+
Node root = tree.buildTree(in, post, n);
94+
System.out.println("Preorder of the constructed tree : ");
95+
tree.preOrder(root);
96+
}
97+
}

0 commit comments

Comments
 (0)