DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 106. Construct Binary Tree from Inorder and Postorder Traversal

Reconstructing a binary tree from its inorder and postorder traversal is a classic recursive problem that tests your understanding of tree traversal patterns and recursion boundaries.


šŸ” What Are Inorder and Postorder?

  • Inorder Traversal (Left → Root → Right)
  • Postorder Traversal (Left → Right → Root)

The last node in postorder is always the root of the tree (or subtree).


šŸ„‡ Approach 1: Basic Recursive with Slicing (Less Efficient)

This version is beginner-friendly and intuitive. It uses array slice() and indexOf(), which makes it less efficient due to repeated array copying and searching.

āœ… Code

function TreeNode(val, left, right) {
    this.val = (val === undefined ? 0 : val);
    this.left = (left === undefined ? null : left);
    this.right = (right === undefined ? null : right);
}

var buildTree = function(inorder, postorder) {
    if (!inorder.length || !postorder.length) return null;

    const rootVal = postorder.pop(); // root from postorder
    const root = new TreeNode(rootVal);

    const mid = inorder.indexOf(rootVal); // find root in inorder

    // Important: build right subtree before left
    root.right = buildTree(inorder.slice(mid + 1), postorder);
    root.left = buildTree(inorder.slice(0, mid), postorder);

    return root;
};
Enter fullscreen mode Exit fullscreen mode

šŸ“Š Time & Space Complexity

  • Time: O(n²)

    • indexOf() takes O(n) for each node.
    • slice() takes O(n) each time.
  • Space: O(n²)

    • Due to array slicing creating new arrays.
    • Call stack can go up to height n.

🄈 Approach 2: Optimized Using Hash Map and Index Bounds

Instead of slicing arrays and searching for index each time, we precompute an index map and work with index boundaries. This reduces overhead drastically.

āœ… Code

function TreeNode(val, left, right) {
    this.val = (val === undefined ? 0 : val);
    this.left = (left === undefined ? null : left);
    this.right = (right === undefined ? null : right);
}

var buildTree = function(inorder, postorder) {
    const inorderMap = new Map();
    inorder.forEach((val, idx) => inorderMap.set(val, idx));

    let postIndex = postorder.length - 1;

    function helper(left, right) {
        if (left > right) return null;

        const rootVal = postorder[postIndex--];
        const root = new TreeNode(rootVal);
        const mid = inorderMap.get(rootVal);

        // Build right subtree before left
        root.right = helper(mid + 1, right);
        root.left = helper(left, mid - 1);

        return root;
    }

    return helper(0, inorder.length - 1);
};
Enter fullscreen mode Exit fullscreen mode

šŸ“Š Time & Space Complexity

  • Time: O(n)

    • Each node is processed once.
    • Index lookup is O(1) using a map.
  • Space: O(n)

    • For the map and recursion stack.

🧠 Summary Comparison

Feature Basic Approach Optimized Approach
Slicing Arrays āœ… Yes āŒ No
Uses Hash Map āŒ No āœ… Yes
Time Complexity āŒ O(n²) āœ… O(n)
Space Complexity āŒ O(n²) āœ… O(n)
Easy to Understand āœ… Yes āš ļø Moderate

✨ Final Thoughts

  • The basic version is great for interviews when you’re warming up or proving your logic.
  • The optimized version is best for production-level or performance-critical use cases.

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Image of Stellar post

šŸš€ Stellar Dev Diaries Series: Episode 1 is LIVE!

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more