Construct Tree from given Postorder and Preorder Traversals in Java

Construct Tree from Postorder and Preorder Traversals

Here we will practice Java Code to Construct Tree from Postorder and Preorder 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 postorder traversal

What are Inorder and Postorder Traversals?

1. Preorder (Root → Left → Right)

First element is always the root

2. Postorder (Left → Right → Root)

Last element is always the root

Construct Tree From Postorder and Preorder Traversal

Given traversals:

Preorder: 50, 25, 12, 37, 30, 40, 75, 62, 60, 70, 87

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

First element in the preorder traversal is the root of the tree. So, here 50 will be the root of the tree.

  1. We will find the index of element next to 50 i.e 25 in the postorder traversal.The index found is 4. Let this index is denoted by ‘pos’.
  2. All the elements to the left of this index and element at this index( i.e from 0 to 4 index) will be in the left subtree of 50.
  3. And all the elements to the right of this index ( from 6 to 10) will be in the right subtree of 50.

Algorithm to Construct Tree from Postorder and Preorder traversals

  1. Pick first element from preorder → root
  2. If only one element → return node
  3. Next preorder element → left subtree root
  4. Find it in postorder
  5. Calculate size of left subtree
  6. Recursively:
    • Build left subtree
    • Build right subtree
  7. Return root

Now, we will divide preorder and postorder array in two parts.

One is for the left subtree and other is for the right subtree.

Let suppose:

  • presi: starting index for preorder array
  • preei: ending index for preorder array
  • postsi: starting index of postorder array
  • postei: ending index of postorder array
  • clc: Number of elements in the left subtree

Clearly, clc= pos – postsi + 1;

For left subtree:
Preorder array: from index presi + 1, presi + clc
Postorder array: from index postsi, pos.

For right subtree:
Preorder array: from index presi + clc + 1, preei
Postorder array: from index pos + 1, postei -1

Using the above arrays, all the steps are recursively repeated.

Construct Tree from given Preorder and Postorder traversals

Pseudocode to Construct Tree from given Traversals

buildTree(preorder, postorder):
    root = preorder[preIndex]
    preIndex++

    if single element:
        return root

    find next preorder element in postorder

    build left subtree
    build right subtree

    return root

Java code to Construct Tree from given Traversals

Run
class Node {
    int data;
    Node left, right;

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

public class ConstructTreePrePost {

    static int preIndex = 0;

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

        if (start > end)
            return null;

        // Create root from preorder
        Node root = new Node(preorder[preIndex++]);

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

        // Next preorder element is left child
        int nextVal = preorder[preIndex];

        // Find it in postorder
        int index = find(postorder, start, end, nextVal);

        // Build left and right subtree
        root.left = buildTree(preorder, postorder, start, index);
        root.right = buildTree(preorder, postorder, index + 1, end - 1);

        return root;
    }

    public static int find(int[] arr, int start, int end, int value) {
        for (int i = start; i <= end; i++) {
            if (arr[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[] preorder = {1, 2, 4, 5, 3, 6, 7};
        int[] postorder = {4, 5, 2, 6, 7, 3, 1};

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

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

Input:

Preorder → 1 2 4 5 3 6 7
Postorder → 4 5 2 6 7 3 1

Constructed Tree:

        1
       / \
      2   3
     / \ / \
    4  5 6  7

Output:

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

Conclusion….

Common Insights:

  1. Preorder gives root
  2. Postorder confirms subtree boundaries
  3. Not always unique tree
  4. Works best for full binary trees

Best Practices:

  1. Always mention non-uniqueness in interviews
  2. Use HashMap for optimization
  3. Validate input size
  4. Prefer recursion for clarity
  5. Test with full binary tree cases

Frequently Asked Questions

Answer:

Not always. A unique tree can only be constructed if the tree is a full binary tree.

Answer:

It is a method to build a binary tree using preorder and postorder traversal arrays under certain conditions.

Answer:

Because preorder and postorder do not provide enough information to distinguish left and right subtree in all cases.

Answer:

It is O(n²) in basic implementation and O(n) with optimization.

Answer:

It is used in tree reconstruction problems, parsing, and also in interviews.

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

Introduction to Trees

Binary Trees

Binary Search Trees

Traversals

  • Traversal in Trees
  • Tree Traversals: Breadth-First Search (BFS) : C | C++ | Java
  • Tree Traversals: Depth First Search (DFS) : C | C++ | Java
  • Construct a Binary Tree from Postorder and Inorder

B – Trees

AVL Trees

  • AVL Trees
    • AVL Trees: Introduction
    • AVL Tree Insertion : C | C++ | Java
    • AVL Tree Deletion : C | C++ | Java
    • Insertion in a Binary Tree (Level Order) – C | C++ | Java
    • Searching in Binary Tree – C | C++ | Java
    • Searching in a Binary Search Tree – C | C++ | Java

Complete Programs for Trees

  • Depth First Traversals – C | C++ | Java
  • Level Order Traversal – C | C++Java
  • Construct Tree from given Inorder and Preorder traversals – C | C++Java
  • Construct Tree from given Postorder and Inorder traversals – C | C++Java
  • Construct Tree from given Postorder and Preorder traversal – C | C++Java
  • Find size of the Binary tree – C | C++Java
  • Find the height of binary tree – C | C++Java
  • Find maximum in binary tree – C | C++Java
  • Check whether two tree are identical- CC++Java
  • Spiral Order traversal of Tree- CC++Java
  • Level Order Traversal Line by Line – C | C++Java
  • Hand shaking lemma and some Impotant Tree Properties.
  • Check If binary tree if Foldable or not.- CC++Java
  • check whether tree is Symmetric – C| C++Java.
  • Check for Children-Sum in Binary Tree- C|C++Java
  • Sum of all nodes in Binary Tree- CC++ | Java
  • Lowest Common Ancestor in Binary Tree- CC++ | Java

Introduction to Trees

Binary Trees

Binary Search Trees

Traversals

  • Traversal in Trees
  • Tree Traversals: Breadth-First Search (BFS) : C | C++ | Java
  • Tree Traversals: Depth First Search (DFS) : C | C++ | Java
  • Construct a Binary Tree from Postorder and Inorder

B – Trees

AVL Trees

  • AVL Trees
    • AVL Trees: Introduction
    • AVL Tree Insertion :  C | C++ | Java
    • AVL Tree Deletion : C | C++ | Java
    • Insertion in a Binary Tree (Level Order) – C | C++ | Java
    • Searching in Binary Tree – C | C++ | Java
    • Searching in a Binary Search Tree – C | C++ | Java

Complete Programs for Trees

  • Depth First Traversals – C | C++ | Java
  • Level Order Traversal – C | C++Java
  • Construct Tree from given Inorder and Preorder traversals – C | C++Java
  • Construct Tree from given Postorder and Inorder traversals – C | C++Java
  • Construct Tree from given Postorder and Preorder traversal – C | C++Java
  • Find size of the Binary tree – C | C++Java
  • Find the height of binary tree – C | C++Java
  • Find maximum in binary tree – C | C++Java
  • Check whether two tree are identical- CC++Java
  • Spiral Order traversal of Tree- CC++Java
  • Level Order Traversal LIne by Line – C | C++Java
  • Hand shaking lemma and some Impotant Tree Properties.
  • Check If binary tree if Foldable or not.- CC++Java
  • check whether tree is Symmetric  C| C++Java.
  • Check for Children-Sum in Binary Tree- C|C++Java
  • Sum of all nodes in Binary Tree- CC++ | Java
  • Lowest Common Ancestor in Binary Tree. CC++ | Java