Construct Tree from given Postorder and Inorder Traversals in Java

Construct Tree From Inorder and Postorder Traversals

Here we will practice Java Code to Construct Tree From Inorder and Postorder Traversals with proper example and algorithm explanation.

At last we have mentioned the Time and space complexity analysis of this topic with some common insights and best ways to practice this concept.

construct a tree from preorder and inorder traversal

What are Inorder and Postorder Traversals?

1. Inorder (Left → Root → Right)

  • Left subtree nodes come first
  • Then root
  • Then right subtree

2. Postorder (Left → Right → Root)

  • Last element is always the root

Construct Tree From Inorder and Postorder Traversals

Example:

Given traversals:

  • Postorder: 12, 30, 40, 37, 25, 60, 70, 62, 87, 75, 50
  • Inorder: 12, 25, 30, 37, 40, 50, 60, 62, 70, 75, 87

The last element in the postorder traversal is the root of the tree. So, here 50 will be the root of the tree.

  • We will find the index of 50 in the inorder traversal.The index found is 5. Let this index is denoted by ‘pos’.
  • All the elements to the left of this index ( from 0 to 4 index) will be in the left subtree of 50.
  • And all the elements to the right of this index ( from 6 to 10) will be in the right subtree of 50.
what is the structure of tree

Algorithm to Construct tree from Inorder and Postorder Traversals

Step by Step Algorithm:

  1. Pick last element from postorder → root
  2. Find root index in inorder array
  3. Elements left → left subtree
  4. Elements right → right subtree
  5. Recursively:
    • Build right subtree
    • Build left subtree
  6. Return root

Learn DSA

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Now, we will divide preorder and inorder array in two parts.
One is for the left subtree and other is for the right subtree.

Let suppose:

  • psi: starting index for preorder array
  • pei: ending index for preorder array
  • isi: starting index of inorder array
  • iei: ending index of preorder array
  • clc: Number of elements in the left subtree

Clearly, clc= pos – isi;

For left subtree:
Postorder array: from index psi, psi + clc – 1
Inorder array: from index isi, isi + clc -1

For right subtree:
Postorder array: from index psi+clc, pei – 1
Inorder array: from index isi + clc + 1, iei

Using the above arrays, all the steps are recursively repeated.
The following binary tree is obtained:

Construct Tree from given Inorder and Postorder traversals

Pseudocode to Construct Tree from given Traversals

buildTree(postorder, inorder):
    if no elements:
        return null

    root = postorder[postIndex]
    postIndex--

    find root index in inorder

    root.right = build right subtree
    root.left = build left subtree

    return root

Java Code to Construct Tree from given Traversals

Run
import java.util.*;

class Node {
    int data;
    Node left, right;

    Node(int value) {
        data = value;
        left = right = null;
    }
}

public class ConstructTreePostIn {

    static int postIndex;

    public static Node buildTree(int[] inorder, int[] postorder, int start, int end) {

        if (start > end)
            return null;

        // Pick root from postorder
        int rootValue = postorder[postIndex--];
        Node root = new Node(rootValue);

        // If leaf node
        if (start == end)
            return root;

        // Find root index in inorder
        int inIndex = search(inorder, start, end, rootValue);

        // Build right subtree first
        root.right = buildTree(inorder, postorder, inIndex + 1, end);
        root.left = buildTree(inorder, postorder, start, inIndex - 1);

        return root;
    }

    public static int search(int[] inorder, int start, int end, int value) {
        for (int i = start; i <= end; i++) {
            if (inorder[i] == value)
                return i;
        }
        return -1;
    }

    // Inorder traversal for verification
    public static void inorderPrint(Node root) {
        if (root == null) return;

        inorderPrint(root.left);
        System.out.print(root.data + " ");
        inorderPrint(root.right);
    }

    public static void main(String[] args) {

        int[] inorder = {4, 2, 5, 1, 3, 6};
        int[] postorder = {4, 5, 2, 6, 3, 1};

        postIndex = postorder.length - 1;

        Node root = buildTree(inorder, postorder, 0, inorder.length - 1);

        System.out.print("Constructed Tree (Inorder): ");
        inorderPrint(root);
    }
}

Input :

Inorder → 4 2 5 1 3 6
Postorder → 4 5 2 6 3 1

Constructed Tree:

        1
       / \
      2   3
     / \   \
    4   5   6

Output :

Constructed Tree (Inorder): 4 2 5 1 3 6

Conclusion….

Common Insights:

  1. Postorder gives root at the end
  2. Inorder divides tree
  3. Right subtree must be built first
  4. Combination uniquely defines tree

Best Practices:

  1. Use HashMap for faster lookup
  2. Always build right subtree first
  3. Avoid duplicate values
  4. Validate traversal arrays
  5. Test edge cases

Frequently Asked Questions

Answer:

It is a method to rebuild a binary tree using inorder (left-root-right) and postorder (left-right-root) traversal arrays.

Answer:

Because we process postorder from the end, which gives root and then right subtree elements.

Answer:

It is O(n²) in the basic approach and O(n) when optimized using a HashMap.

Answer:

No, we need at least two traversals (like inorder + postorder) to uniquely construct a tree.

Answer:

It is used in expression trees, parsing, compilers, and serialization systems.

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

Construct Tree from given Postorder and Inorder traversals in C

Construct Tree from given Postorder and Inorder Traversals

On this page we wiil discuss about how to construct tree from given postorder and inorder traversals in C .

There are three types of traversals in a tree: Inorder, Preorder and Postorder traversal. A tree can be formed with any two tree traversals in which one of them being the in order traversal.

Postorder Traversal: We first  move to the left subtree and then to the right subtree and finally print the node.
Inorder Traversal: We move to the left subtree, then print the node and move to the right subtree.

postorder inorder traversal

Tree From Given Postorder and Inorder Traversal

Algorithm For InOrder Traversal

  • Traverse The Left subtree.
  • Print the node.
  • Traverse the right subtree.

Algorithm For PostOrder Traversal

  • Traverse the left subtree.
  • Traverse the right subtree.
  • Print the node.

Algorithm for tree construction:

  • Start with root node, which will be the last element in the postorder sequence
  •  And find the boundary of its left and right subtree in the inorder sequence.
  • To find the boundary, search for the index of the root node in the inorder sequence.
  • All keys before the root node in the inorder sequence become part of the left subtree, and all the keys after the root node become part of the right subtree.
  • Repeat the above step recursively for all the nodes in the tree and construct the tree.
Construct Tree from given Postorder and Inorder Traversals in C++

Code in C to Construct Tree from given Postorder and Inorder Traversals

Run
#include <stdio.h>
#include <stdlib.h>
 
// Data structure to store a binary tree node
struct Node
{
    int key;
    struct Node *left, *right;
};
 
// Function to create a new binary tree node having a given key
struct Node* newNode(int key)
{
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));
    node->key = key;
    node->left = node->right = NULL;
 
    return node;
}
 
// Recursive function to perform inorder traversal on a given binary tree
void inorderTraversal(struct Node* root)
{
    if (root == NULL) {
        return;
    }
 
    inorderTraversal(root->left);
    printf("%d ", root->key);
    inorderTraversal(root->right);
}
 
// Recursive function to perform postorder traversal on a given binary tree
void postorderTraversal(struct Node* root)
{
    if (root == NULL) {
        return;
    }
 
    postorderTraversal(root->left);
    postorderTraversal(root->right);
    printf("%d ", root->key);
}
 
// Recursive function to construct a binary tree from a given
// inorder and postorder traversals
struct Node* construct(int inorder[], int start, int end,
                    int postorder[], int *pIndex)
{
    // base case
    if (start > end) {
        return NULL;
    }
 
    // Consider the next item from the end of a given postorder sequence.
    // This value would be the root node of the subtree formed by the sequence
    // inorder[start, end].
    struct Node* node = newNode(postorder[(*pIndex)--]);
 
    // search the current node index in inorder sequence to determine
    // the boundary of the left and right subtree of the current node
    int i;
    for (i = start; i <= end; i++)
    {
        if (inorder[i] == node->key) {
            break;
        }
    }
 
    // recursively construct the right subtree
    node->right= construct(inorder, i + 1, end, postorder, pIndex);
 
    // recursively construct the left subtree
    node->left = construct(inorder, start, i - 1, postorder, pIndex);
 
    // return the current node
    return node;
}
 
// Construct a binary tree from inorder and postorder traversals.
// This function assumes that the input is valid, i.e., given
// inorder and postorder sequences forming a binary tree.
struct Node* constructTree(int inorder[], int postorder[], int n)
{
    // `pIndex` stores the index of the next unprocessed node from the end
    // of the postorder sequence
    int *pIndex = &n;
    return construct(inorder, 0, n, postorder, pIndex);
}
 
int main(void)
{
    /* Construct the following tree
               1
             /   \
            /     \
           2       3
          /       / \
         /       /   \
        4       5     6
               / \
              /   \
             7     8
    */
 
    int inorder[]    = { 4, 2, 1, 7, 5, 8, 3, 6 };
    int postorder[] = { 4, 2, 7, 8, 5, 6, 3, 1 };
    int n = sizeof(inorder)/sizeof(inorder[0]);
 
    struct Node* root = constructTree(inorder, postorder, n - 1);
 
    // traverse the constructed tree
    printf("Inorder traversal is "); inorderTraversal(root);
    printf("\nPostorder traversal is "); postorderTraversal(root);
 
    return 0;
}

Output:

Inorder traversal is 4 2 1 7 5 8 3 6 
Postorder traversal is 4 2 7 8 5 6 3 1