Construct a tree for the given inorder and postorder traversals: Inorder: DGBHEICF Postorder: GDBHIEFC


Q.) Construct a tree for the given inorder and postorder traversals: Inorder: DGBHEICF Postorder: GDBHIEFC

Subject: Data Structures

To construct a binary tree from given inorder and postorder traversals, we need to follow these steps:

  1. Start from the last item of postorder traversal which is the root of the tree.
  2. Search for the root in inorder traversal and divide it into two halves. The left half will be the left subtree and the right half will be the right subtree.
  3. Repeat the above two steps for the halves. The first item of the postorder traversal will be the root of the left subtree and the last item before the root in the postorder traversal will be the root of the right subtree.

Let's follow these steps for the given inorder and postorder traversals:

Inorder: DGBHEICF Postorder: GDBHIEFC

Step 1: The last item in the postorder traversal is 'C'. So, 'C' is the root of the tree.

Step 2: In the inorder traversal, 'C' divides the traversal into two halves 'DGBHEI' and 'F'. So, 'DGBHEI' will be the left subtree and 'F' will be the right subtree.

Step 3: Repeat the above two steps for the halves.

For the left subtree 'DGBHEI':

The last item in the postorder traversal before 'C' is 'E'. So, 'E' is the root of the left subtree.

In the inorder traversal, 'E' divides the traversal into two halves 'DGBH' and 'I'. So, 'DGBH' will be the left subtree and 'I' will be the right subtree of 'E'.

For the right subtree 'F':

There is only one node 'F'. So, 'F' is the leaf node.

The final binary tree will look like this:

     C
   /   \
  E     F
 / \
DGBH  I

Note: The left subtree 'DGBH' can be further divided into smaller subtrees following the same steps. The final binary tree will be:

     C
   /   \
  E     F
 / \
B   I
 / \
D   H
   /
  G