Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Construct a binary tree from given In-Order and Post-Order Traversal

Given In-Order and Post-Order traversal for a binary tree, we can construct the binary tree from it. The
procedure is simple and recursive.
The steps mainly requires finding the root node in every iteration.
The process of finding the root node is done with the help of Post-Order traversal. The point to be noted
here is that the Post-Order traversal always holds the root node at the end.
Algorithm for Constructing a Binary tree from In-Order and Post-Order Traversal:

1. Last element in the Post-Order traversal will be the root of the tree.
2. Now search for the same root element in In-Order, let it be found at position i, once it is found, make
note of elements which are left to i (this will construct the left Subtree) and elements which are right
to i ( this will construct the right Subtree).
3. Suppose in previous step, there are X number of elements which are left of ‘i’ (which will construct
the left subtree), take first X elements from the Post Order traversal, this will be the Post Order
traversal for elements which are left to i.
4. Similarly if there are Y number of elements which are right of ‘i’ (which will construct the right
subtree), take next Y elements, after X elements from the Post Order traversal, this will be the post
order traversal for elements which are right to i
5. From previous two steps construct the left and right subtree and link it to rootLeft and rootright
respectively.
6. Repeat the same steps until all elements in In-Order and Post-Order completed.

Example – 1: Construct a Binary Tree with the following traversal sequences.


In-Order: 4, 2, 5, 1, 6, 3, 7
Post-Order: 4, 5, 2, 6, 7, 3, 1
Step – 1:

Insert 1 as the root node to the Binary Tree


Step – 2:

Insert 2 as left node and 3 as right node to root node 1.

Step – 3:

Insert 4 as left to 2 and 5 as right to 2.


Insert 6 as left to 3 and 7 as right to 3
Example – 2: Construct a Binary Tree with the following traversal sequences.
In-Order: G C R O A I H T M
Post-Order: G R O C H M T I A
Step – 1:

Insert A as root node to the Binary Tree

Step – 2:

Insert C as left node and I as right node to root node A.

Step – 3:
Insert G as left child and O as right child to C.
Insert T as right child to I.

Step – 4:

Insert R as left child to O.


Insert H as left child and M as right child to T.

You might also like