Open In App

JavaScript Program to Construct a Binary Tree from Inorder & Postorder Traversal

Last Updated : 09 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given the inorder and postorder traversal sequences of a binary tree, the task is to construct the binary tree.

Example:

Inorder traversal: [9,3,15,20,7]
Postorder traversal: [9,15,7,20,3]

Binary Tree:
3
/ \
9 20
/ \
15 7

Below are the approaches to constructing a binary tree from Inorder and Postorder traversal:

Recursive Approach

This approach recursively builds the binary tree by selecting the last element from the Postorder traversal as the root, finding its index in the Inorder traversal to determine the left and right subtrees and then recursively constructing the left and right subtrees.

Steps:

  • Find the root node which is last element from Postorder traversal sequence.
  • Find the index of the root node in the Inorder traversal.
  • Recursively build the left subtree using elements to the left of the root in the Inorder traversal and elements to the left of the root in the Postorder traversal.
  • Recursively build the right subtree using elements to the right of the root in the Inorder traversal and elements to the right of the root in the Postorder traversal.

Example: This example uses recursive approach to construct binary tree from Inorder and Postorder traversal.

JavaScript
function TreeNode(val) {
    this.val = val;
    this.left = null;
    this.right = null;
}

function binaryTree(inorder, postorder) {
    if (postorder.length === 0) {
        return null;
    }

    const val = postorder[postorder.length - 1];
    const node = new TreeNode(val);

    const idx = inorder
        .indexOf(val);
    const leftInorder = inorder
        .slice(0, idx);
    const rightInorder = inorder
        .slice(idx + 1);

    const leftPostorder = postorder
        .slice(0, leftInorder.length);
    const rightPostorder = postorder
        .slice(leftInorder.length, postorder.length - 1);

    node.left = binaryTree(leftInorder, leftPostorder);
    node.right = binaryTree(rightInorder, rightPostorder);

    return node;
}

function printPreorder(node) {
    if (node === null) {
        return '';
    }
    let result = node
        .val + ' ';
    result += printPreorder(node.left);
    result += printPreorder(node.right);
    return result;
}


const inorder = [9, 3, 15, 20, 7];
const postorder = [9, 15, 7, 20, 3];
const tree = binaryTree(inorder, postorder);
console.log(printPreorder(tree));

Output
3 9 20 15 7 

Time Complexity: O(n^2)

Space Complexity: O(n)

Iterative approach

This approach uses a stack to iteratively build the binary tree by using the recursive approach. It iterates through the Postorder traversal in reverse order using a stack to keep track of nodes and their children until the tree is fully constructed.

Steps:

  • Start with an empty stack and set the last element of the Postorder traversal as the root of the tree.
  • Loop through the remaining elements of the Postorder traversal in reverse (from the second-last element to the first).
  • For each element create a new node for the current element. If the current node’s value is less than the stack’s top node’s value, set the current node as the left child of the stack’s top node. If the current node’s value is greater, keep popping nodes from the stack and set the last popped node’s right child as the current nod, until the stack’s top node’s value is greater than the current node’s value. Push the current node onto the stack.
  • Repeat step 3 for all remaining elements.
  • The stack will contain the root of the constructed binary tree.

Example: This example uses iterative approach to construct binary tree from Inorder and Postorder traversal.

JavaScript
class TreeNode {
    constructor(val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

function binaryTree(inorder, postorder)
{
    if (!inorder.length || !postorder.length)
    {
        return null;
    }

    const stack = [];
    const rootVal = postorder[postorder.length - 1];
    const root = new TreeNode(rootVal);
    stack
    .push(root);

    let inorderIndex = inorder
    .length - 1;
    for (let i = postorder.length - 2; i >= 0; i--) 
    {
        let currVal = postorder[i];
        let node = stack[stack.length - 1];

        if (node.val !== inorder[inorderIndex])
        {
            node
            .right = new TreeNode(currVal);
            stack
            .push(node.right);
        } else {
            while (stack.length && stack[stack.length - 1]
                .val === inorder[inorderIndex]) 
            {
                node = stack.pop();
                inorderIndex--;
            }
            node.left = new TreeNode(currVal);
            stack.push(node.left);
        }
    }

    return root;
}

function printPreorder(node) {
    if (node === null) {
        return '';
    }
    let result = node.val + ' ';
    result += printPreorder(node.left);
    result += printPreorder(node.right);
    return result;
}

const inorder = [4,2,1,5,3];
const postorder = [4,2,5,3,1];
const tree = binaryTree(inorder, postorder);
console.log(printPreorder(tree));

Output
1 2 4 3 5 

Time Complexity: O(n)

Space Complexity: O(n)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads