The Wayback Machine - https://web.archive.org/web/20240823033409/https://www.geeksforgeeks.org/construct-a-binary-tree-from-postorder-and-inorder/
Open In App

Construct a Binary Tree from Postorder and Inorder

Last Updated : 24 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
64.78%
78.1K

Given Postorder and Inorder traversals, construct the tree.

Examples: 

Input: 
in[]   = {2, 1, 3}
post[] = {2, 3, 1}

Output: Root of below tree

      1
    /   \
  2     3 

Input: 
in[]   = {4, 8, 2, 5, 1, 6, 3, 7}
post[] = {8, 4, 5, 2, 6, 7, 3, 1} 

Output: Root of below tree

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

Approach: To solve the problem follow the below idea:

Note: We have already discussed the construction of trees from Inorder and Preorder traversals:

Follow the below steps:

Let us see the process of constructing a tree from in[] = {4, 8, 2, 5, 1, 6, 3, 7} and post[] = {8, 4, 5, 2, 6, 7, 3, 1}:

  • We first find the last node in post[]. The last node is “1”, we know this value is the root as the root always appears at the end of postorder traversal.
  • We search “1” in in[] to find the left and right subtrees of the root. Everything on the left of “1” in in[] is in the left subtree and everything on right is in the right subtree. 

            1
          /    \
[4, 8, 2, 5]   [6, 3, 7]

  • We recur the above process for the following two. 
    • Recur for in[] = {6, 3, 7} and post[] = {6, 7, 3} Make the created tree as right child of root. 
    • Recur for in[] = {4, 8, 2, 5} and post[] = {8, 4, 5, 2}. Make the created tree the left child of the root.

Note: One important observation is, that we recursively call for the right subtree before the left subtree as we decrease the index of the postorder index whenever we create a new node

Below is the implementation of the above approach: 

C++




/* C++ program to construct tree using inorder and
   postorder traversals */
#include <bits/stdc++.h>
 
using namespace std;
 
/* A binary tree node has data, pointer to left
   child and a pointer to right child */
struct Node {
    int data;
    Node *left, *right;
};
 
// Utility function to create a new node
Node* newNode(int data);
 
/* Prototypes for utility functions */
int search(int arr[], int strt, int end, int value);
 
/* Recursive function to construct binary of size n
   from  Inorder traversal in[] and Postorder traversal
   post[].  Initial values of inStrt and inEnd should
   be 0 and n -1.  The function doesn't do any error
   checking for cases where inorder and postorder
   do not form a tree */
Node* buildUtil(int in[], int post[], int inStrt, int inEnd,
                int* pIndex)
{
    // Base case
    if (inStrt > inEnd)
        return NULL;
 
    /* Pick current node from Postorder traversal using
       postIndex and decrement postIndex */
    Node* node = newNode(post[*pIndex]);
    (*pIndex)--;
 
    /* If this node has no children then return */
    if (inStrt == inEnd)
        return node;
 
    /* Else find the index of this node in Inorder
       traversal */
    int iIndex = search(in, inStrt, inEnd, node->data);
 
    /* Using index in Inorder traversal, construct left and
       right subtrees */
    node->right
        = buildUtil(in, post, iIndex + 1, inEnd, pIndex);
    node->left
        = buildUtil(in, post, inStrt, iIndex - 1, pIndex);
 
    return node;
}
 
// This function mainly initializes index of root
// and calls buildUtil()
Node* buildTree(int in[], int post[], int n)
{
    int pIndex = n - 1;
    return buildUtil(in, post, 0, n - 1, &pIndex;);
}
 
/* Function to find index of value in arr[start...end]
   The function assumes that value is postsent in in[] */
int search(int arr[], int strt, int end, int value)
{
    int i;
    for (i = strt; i <= end; i++) {
        if (arr[i] == value)
            break;
    }
    return i;
}
 
/* Helper function that allocates a new node */
Node* newNode(int data)
{
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
 
/* This function is here just to test  */
void preOrder(Node* node)
{
    if (node == NULL)
        return;
    printf("%d ", node->data);
    preOrder(node->left);
    preOrder(node->right);
}
 
// Driver code
int main()
{
    int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 };
    int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 };
    int n = sizeof(in) / sizeof(in[0]);
 
    Node* root = buildTree(in, post, n);
 
    cout << "Preorder of the constructed tree : \n";
    preOrder(root);
 
    return 0;
}


Java




// Java program to construct a tree using inorder
// and postorder traversals
 
/* A binary tree node has data, pointer to left
   child and a pointer to right child */
class Node {
    int data;
    Node left, right;
 
    public Node(int data)
    {
        this.data = data;
        left = right = null;
    }
}
 
class BinaryTree {
    /* Recursive function to construct binary of size n
       from  Inorder traversal in[] and Postorder traversal
       post[]. Initial values of inStrt and inEnd should
       be 0 and n -1.  The function doesn't do any error
       checking for cases where inorder and postorder
       do not form a tree */
    Node buildUtil(int in[], int post[], int inStrt,
                   int inEnd, int postStrt, int postEnd)
    {
        // Base case
        if (inStrt > inEnd)
            return null;
 
        /* Pick current node from Postorder traversal using
           postIndex and decrement postIndex */
        Node node = new Node(post[postEnd]);
 
        /* If this node has no children then return */
        if (inStrt == inEnd)
            return node;
        int iIndex = search(in, inStrt, inEnd, node.data);
 
        /* Using index in Inorder traversal, construct left
           and right subtrees */
        node.left = buildUtil(
            in, post, inStrt, iIndex - 1, postStrt,
            postStrt - inStrt + iIndex - 1);
        node.right = buildUtil(in, post, iIndex + 1, inEnd,
                               postEnd - inEnd + iIndex,
                               postEnd - 1);
 
        return node;
    }
 
    /* Function to find index of value in arr[start...end]
       The function assumes that value is postsent in in[]
     */
    int search(int arr[], int strt, int end, int value)
    {
        int i;
        for (i = strt; i <= end; i++) {
            if (arr[i] == value)
                break;
        }
        return i;
    }
 
    /* This function is here just to test  */
    void preOrder(Node node)
    {
        if (node == null)
            return;
        System.out.print(node.data + " ");
        preOrder(node.left);
        preOrder(node.right);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        BinaryTree tree = new BinaryTree();
        int in[] = new int[] { 4, 8, 2, 5, 1, 6, 3, 7 };
        int post[] = new int[] { 8, 4, 5, 2, 6, 7, 3, 1 };
        int n = in.length;
        Node root
            = tree.buildUtil(in, post, 0, n - 1, 0, n - 1);
        System.out.println(
            "Preorder of the constructed tree : ");
        tree.preOrder(root);
    }
}
 
// This code has been contributed by Mayank
// Jaiswal(mayank_24)


Python3




# Python3 program to construct tree using
# inorder and postorder traversals
 
# Helper function that allocates
# a new node
 
 
class newNode:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
 
# Recursive function to construct binary
# of size n from Inorder traversal in[]
# and Postorder traversal post[]. Initial
# values of inStrt and inEnd should be
# 0 and n -1. The function doesn't do any
# error checking for cases where inorder
# and postorder do not form a tree
 
 
def buildUtil(In, post, inStrt, inEnd, pIndex):
 
    # Base case
    if (inStrt > inEnd):
        return None
 
    # Pick current node from Postorder traversal
    # using postIndex and decrement postIndex
    node = newNode(post[pIndex[0]])
    pIndex[0] -= 1
 
    # If this node has no children
    # then return
    if (inStrt == inEnd):
        return node
 
    # Else find the index of this node
    # in Inorder traversal
    iIndex = search(In, inStrt, inEnd, node.data)
 
    # Using index in Inorder traversal,
    # construct left and right subtress
    node.right = buildUtil(In, post, iIndex + 1,
                           inEnd, pIndex)
    node.left = buildUtil(In, post, inStrt,
                          iIndex - 1, pIndex)
 
    return node
 
# This function mainly initializes index
# of root and calls buildUtil()
 
 
def buildTree(In, post, n):
    pIndex = [n - 1]
    return buildUtil(In, post, 0, n - 1, pIndex)
 
# Function to find index of value in
# arr[start...end]. The function assumes
# that value is postsent in in[]
 
 
def search(arr, strt, end, value):
    i = 0
    for i in range(strt, end + 1):
        if (arr[i] == value):
            break
    return i
 
# This function is here just to test
 
 
def preOrder(node):
    if node == None:
        return
    print(node.data, end=" ")
    preOrder(node.left)
    preOrder(node.right)
 
 
# Driver code
if __name__ == '__main__':
    In = [4, 8, 2, 5, 1, 6, 3, 7]
    post = [8, 4, 5, 2, 6, 7, 3, 1]
    n = len(In)
 
    root = buildTree(In, post, n)
 
    print("Preorder of the constructed tree :")
    preOrder(root)
 
# This code is contributed by PranchalK


C#




// C# program to construct a tree using
// inorder and postorder traversals
using System;
 
/* A binary tree node has data, pointer
to left child and a pointer to right child */
public class Node {
    public int data;
    public Node left, right;
 
    public Node(int data)
    {
        this.data = data;
        left = right = null;
    }
}
 
// Class Index created to implement
// pass by reference of Index
public class Index {
    public int index;
}
 
class GFG {
    /* Recursive function to construct binary
    of size n from Inorder traversal in[] and
    Postorder traversal post[]. Initial values
    of inStrt and inEnd should be 0 and n -1.
    The function doesn't do any error checking
    for cases where inorder and postorder do
    not form a tree */
    public virtual Node buildUtil(int[] @in, int[] post,
                                  int inStrt, int inEnd,
                                  Index pIndex)
    {
        // Base case
        if (inStrt > inEnd) {
            return null;
        }
 
        /* Pick current node from Postorder traversal
        using postIndex and decrement postIndex */
        Node node = new Node(post[pIndex.index]);
        (pIndex.index)--;
 
        /* If this node has no children
        then return */
        if (inStrt == inEnd) {
            return node;
        }
 
        /* Else find the index of this node
        in Inorder traversal */
        int iIndex = search(@in, inStrt, inEnd, node.data);
 
        /* Using index in Inorder traversal,
        construct left and right subtrees */
        node.right = buildUtil(@in, post, iIndex + 1, inEnd,
                               pIndex);
        node.left = buildUtil(@in, post, inStrt, iIndex - 1,
                              pIndex);
 
        return node;
    }
 
    // This function mainly initializes
    // index of root and calls buildUtil()
    public virtual Node buildTree(int[] @in, int[] post,
                                  int n)
    {
        Index pIndex = new Index();
        pIndex.index = n - 1;
        return buildUtil(@in, post, 0, n - 1, pIndex);
    }
 
    /* Function to find index of value in
    arr[start...end]. The function assumes
    that value is postsent in in[] */
    public virtual int search(int[] arr, int strt, int end,
                              int value)
    {
        int i;
        for (i = strt; i <= end; i++) {
            if (arr[i] == value) {
                break;
            }
        }
        return i;
    }
 
    /* This function is here just to test */
    public virtual void preOrder(Node node)
    {
        if (node == null) {
            return;
        }
        Console.Write(node.data + " ");
        preOrder(node.left);
        preOrder(node.right);
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        GFG tree = new GFG();
        int[] @in = new int[] { 4, 8, 2, 5, 1, 6, 3, 7 };
        int[] post = new int[] { 8, 4, 5, 2, 6, 7, 3, 1 };
        int n = @in.Length;
        Node root = tree.buildTree(@in, post, n);
        Console.WriteLine(
            "Preorder of the constructed tree : ");
        tree.preOrder(root);
    }
}
 
// This code is contributed by Shrikant13


Javascript




<script>
// Javascript program to construct a tree using inorder
// and postorder traversals
     
    /* A binary tree node has data, pointer to left
   child and a pointer to right child */
    class Node
    {
        constructor(data)
        {
            this.data = data;
            this.left = this.right = null;
        }
    }
     
    /* Recursive function to construct binary of size n
       from  Inorder traversal in[] and Postorder traversal
       post[]. Initial values of inStrt and inEnd should
       be 0 and n -1.  The function doesn't do any error
       checking for cases where inorder and postorder
       do not form a tree */
    function buildUtil(In, post, inStrt, inEnd, postStrt, postEnd)
    {
     
        // Base case
        if (inStrt > inEnd)
            return null;
  
        /* Pick current node from Postorder traversal using
           postIndex and decrement postIndex */
        let node = new Node(post[postEnd]);
  
        /* If this node has no children then return */
        if (inStrt == inEnd)
            return node;
        let iIndex = search(In, inStrt, inEnd, node.data);
  
        /* Using index in Inorder traversal, construct left
           and right subtrees */
        node.left = buildUtil(
            In, post, inStrt, iIndex - 1, postStrt,
            postStrt - inStrt + iIndex - 1);
        node.right = buildUtil(In, post, iIndex + 1, inEnd,
                               postEnd - inEnd + iIndex,
                               postEnd - 1);
  
        return node;
    }
     
    /* Function to find index of value in arr[start...end]
       The function assumes that value is postsent in in[]
     */
    function search(arr,strt,end,value)
    {
        let i;
        for (i = strt; i <= end; i++) {
            if (arr[i] == value)
                break;
        }
        return i;
    }
     
    /* This function is here just to test  */
    function preOrder(node)
    {
        if (node == null)
            return;
        document.write(node.data + " ");
        preOrder(node.left);
        preOrder(node.right);
    }
     
    // Driver Code
    let In=[4, 8, 2, 5, 1, 6, 3, 7];
    let post=[8, 4, 5, 2, 6, 7, 3, 1];
    let n = In.length;
    let root
            = buildUtil(In, post, 0, n - 1, 0, n - 1);
    document.write(
            "Preorder of the constructed tree : <br>");
    preOrder(root);
     
    // This code is contributed by unknown2108
</script>


Output

Preorder of the constructed tree : 
1 2 4 8 5 3 6 7

Time Complexity: O(N2), Where N is the length of the given inorder array
Auxiliary Space: O(N), for recursive call stack

Construct a Binary Tree from Postorder and Inorder using hashing:

To solve the problem follow the below idea:

We can optimize the above solution using hashing. We store indexes of inorder traversal in a hash table. So that search can be done O(1) time If given that element in the tree is not repeated.

Follow the below steps to solve the problem:

  • We first find the last node in post[]. The last node is “1”, we know this value is the root as the root always appears at the end of postorder traversal.
  • we get the index of postorder[i], in inorder using the map to find the left and right subtrees of the root. Everything on the left of “1” in in[] is in the left subtree and everything on right is in the right subtree. 
  • We recur the above process for the following two. 
    • Recur for in[] = {6, 3, 7} and post[] = {6, 7, 3} Make the created tree as right child of root. 
    • Recur for in[] = {4, 8, 2, 5} and post[] = {8, 4, 5, 2}. Make the created tree the left child of the root.

Below is the implementation of the above approach:

C++




/* C++ program to construct tree using inorder and
postorder traversals */
#include <bits/stdc++.h>
 
using namespace std;
 
/* A binary tree node has data, pointer to left
child and a pointer to right child */
struct Node {
    int data;
    Node *left, *right;
};
 
// Utility function to create a new node
Node* newNode(int data);
 
/* Recursive function to construct binary of size n
from Inorder traversal in[] and Postorder traversal
post[]. Initial values of inStrt and inEnd should
be 0 and n -1. The function doesn't do any error
checking for cases where inorder and postorder
do not form a tree */
Node* buildUtil(int in[], int post[], int inStrt, int inEnd,
                int* pIndex, unordered_map<int, int>& mp)
{
    // Base case
    if (inStrt > inEnd)
        return NULL;
 
    /* Pick current node from Postorder traversal
    using postIndex and decrement postIndex */
    int curr = post[*pIndex];
    Node* node = newNode(curr);
    (*pIndex)--;
 
    /* If this node has no children then return */
    if (inStrt == inEnd)
        return node;
 
    /* Else find the index of this node in Inorder
    traversal */
    int iIndex = mp[curr];
 
    /* Using index in Inorder traversal, construct
    left and right subtrees */
    node->right = buildUtil(in, post, iIndex + 1, inEnd,
                            pIndex, mp);
    node->left = buildUtil(in, post, inStrt, iIndex - 1,
                           pIndex, mp);
 
    return node;
}
 
// This function mainly creates an unordered_map, then
// calls buildTreeUtil()
struct Node* buildTree(int in[], int post[], int len)
{
    // Store indexes of all items so that we
    // we can quickly find later
    unordered_map<int, int> mp;
    for (int i = 0; i < len; i++)
        mp[in[i]] = i;
 
    int index = len - 1; // Index in postorder
    return buildUtil(in, post, 0, len - 1, &index;, mp);
}
 
/* Helper function that allocates a new node */
Node* newNode(int data)
{
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
 
/* This function is here just to test */
void preOrder(Node* node)
{
    if (node == NULL)
        return;
    printf("%d ", node->data);
    preOrder(node->left);
    preOrder(node->right);
}
 
// Driver code
int main()
{
    int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 };
    int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 };
    int n = sizeof(in) / sizeof(in[0]);
 
    Node* root = buildTree(in, post, n);
 
    cout << "Preorder of the constructed tree : \n";
    preOrder(root);
 
    return 0;
}


Java




/* Java program to construct tree using inorder and
postorder traversals */
import java.util.*;
class GFG {
 
    /* A binary tree node has data, pointer to left
    child and a pointer to right child */
    static class Node {
        int data;
        Node left, right;
    };
 
    // Utility function to create a new node
    /* Helper function that allocates a new node */
    static Node newNode(int data)
    {
        Node node = new Node();
        node.data = data;
        node.left = node.right = null;
        return (node);
    }
 
    /* Recursive function to construct binary of size n
    from Inorder traversal in[] and Postorder traversal
    post[]. Initial values of inStrt and inEnd should
    be 0 and n -1. The function doesn't do any error
    checking for cases where inorder and postorder
    do not form a tree */
    static Node buildUtil(int in[], int post[], int inStrt,
                          int inEnd)
    {
 
        // Base case
        if (inStrt > inEnd)
            return null;
 
        /* Pick current node from Postorder traversal
        using postIndex and decrement postIndex */
        int curr = post[index];
        Node node = newNode(curr);
        (index)--;
 
        /* If this node has no children then return */
        if (inStrt == inEnd)
            return node;
 
        /* Else find the index of this node in Inorder
        traversal */
        int iIndex = mp.get(curr);
 
        /* Using index in Inorder traversal, con
        left and right subtrees */
        node.right = buildUtil(in, post, iIndex + 1, inEnd);
        node.left = buildUtil(in, post, inStrt, iIndex - 1);
        return node;
    }
    static HashMap<Integer, Integer> mp
        = new HashMap<Integer, Integer>();
    static int index;
 
    // This function mainly creates an unordered_map, then
    // calls buildTreeUtil()
    static Node buildTree(int in[], int post[], int len)
    {
 
        // Store indexes of all items so that we
        // we can quickly find later
        for (int i = 0; i < len; i++)
            mp.put(in[i], i);
 
        index = len - 1; // Index in postorder
        return buildUtil(in, post, 0, len - 1);
    }
 
    /* This function is here just to test */
    static void preOrder(Node node)
    {
        if (node == null)
            return;
        System.out.printf("%d ", node.data);
        preOrder(node.left);
        preOrder(node.right);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 };
        int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 };
        int n = in.length;
        Node root = buildTree(in, post, n);
        System.out.print(
            "Preorder of the constructed tree : \n");
        preOrder(root);
    }
}
 
// This code is contributed by Rajput-Ji


Python3




# Python3 program to construct tree using inorder
# and postorder traversals
 
# A binary tree node has data, pointer to left
# child and a pointer to right child
 
 
class Node:
 
    def __init__(self, x):
 
        self.data = x
        self.left = None
        self.right = None
 
# Recursive function to construct binary of size n
# from Inorder traversal in[] and Postorder traversal
# post[]. Initial values of inStrt and inEnd should
# be 0 and n -1. The function doesn't do any error
# checking for cases where inorder and postorder
# do not form a tree
 
 
def buildUtil(inn, post, innStrt, innEnd):
 
    global mp, index
 
    # Base case
    if (innStrt > innEnd):
        return None
 
    # Pick current node from Postorder traversal
    # using postIndex and decrement postIndex
    curr = post[index]
    node = Node(curr)
    index -= 1
 
    # If this node has no children then return
    if (innStrt == innEnd):
        return node
 
    # Else find the index of this node inn
    # Inorder traversal
    iIndex = mp[curr]
 
    # Using index in Inorder traversal,
    # construct left and right subtrees
    node.right = buildUtil(inn, post,
                           iIndex + 1, innEnd)
    node.left = buildUtil(inn, post, innStrt,
                          iIndex - 1)
 
    return node
 
# This function mainly creates an unordered_map,
# then calls buildTreeUtil()
 
 
def buildTree(inn, post, lenn):
 
    global index
 
    # Store indexes of all items so that we
    # we can quickly find later
    for i in range(lenn):
        mp[inn[i]] = i
 
    # Index in postorder
    index = lenn - 1
    return buildUtil(inn, post, 0, lenn - 1)
 
# This function is here just to test
 
 
def preOrder(node):
 
    if (node == None):
        return
 
    print(node.data, end=" ")
    preOrder(node.left)
    preOrder(node.right)
 
 
# Driver Code
if __name__ == '__main__':
 
    inn = [4, 8, 2, 5, 1, 6, 3, 7]
    post = [8, 4, 5, 2, 6, 7, 3, 1]
    n = len(inn)
    mp, index = {}, 0
 
    root = buildTree(inn, post, n)
 
    print("Preorder of the constructed tree :")
    preOrder(root)
 
# This code is contributed by mohit kumar 29


C#




/* C# program to construct tree using inorder and
postorder traversals */
using System;
using System.Collections.Generic;
class GFG {
 
    /* A binary tree node has data, pointer to left
  child and a pointer to right child */
    public
 
        class Node {
        public
 
            int data;
        public
 
            Node left,
            right;
    };
 
    // Utility function to create a new node
    /* Helper function that allocates a new node */
    static Node newNode(int data)
    {
        Node node = new Node();
        node.data = data;
        node.left = node.right = null;
        return (node);
    }
 
    /* Recursive function to construct binary of size n
  from Inorder traversal in[] and Postorder traversal
  post[]. Initial values of inStrt and inEnd should
  be 0 and n -1. The function doesn't do any error
  checking for cases where inorder and postorder
  do not form a tree */
    static Node buildUtil(int[] init, int[] post,
                          int inStrt, int inEnd)
    {
 
        // Base case
        if (inStrt > inEnd)
            return null;
 
        /* Pick current node from Postorder traversal
        using postIndex and decrement postIndex */
        int curr = post[index];
        Node node = newNode(curr);
        (index)--;
 
        /* If this node has no children then return */
        if (inStrt == inEnd)
            return node;
 
        /* Else find the index of this node in Inorder
        traversal */
        int iIndex = mp[curr];
 
        /* Using index in Inorder traversal, con
        left and right subtrees */
        node.right
            = buildUtil(init, post, iIndex + 1, inEnd);
        node.left
            = buildUtil(init, post, inStrt, iIndex - 1);
        return node;
    }
    static Dictionary<int, int> mp
        = new Dictionary<int, int>();
    static int index;
 
    // This function mainly creates an unordered_map, then
    // calls buildTreeUtil()
    static Node buildTree(int[] init, int[] post, int len)
    {
 
        // Store indexes of all items so that we
        // we can quickly find later
        for (int i = 0; i < len; i++)
            mp.Add(init[i], i);
 
        index = len - 1; // Index in postorder
        return buildUtil(init, post, 0, len - 1);
    }
 
    /* This function is here just to test */
    static void preOrder(Node node)
    {
        if (node == null)
            return;
        Console.Write(node.data + " ");
        preOrder(node.left);
        preOrder(node.right);
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int[] init = { 4, 8, 2, 5, 1, 6, 3, 7 };
        int[] post = { 8, 4, 5, 2, 6, 7, 3, 1 };
        int n = init.Length;
        Node root = buildTree(init, post, n);
        Console.Write(
            "Preorder of the constructed tree : \n");
        preOrder(root);
    }
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
 
      /* JavaScript program to construct tree using inorder and
      postorder traversals */
      /* A binary tree node has data, pointer to left
      child and a pointer to right child */
      class Node {
        constructor() {
          this.data = 0;
          this.left = null;
          this.right = null;
        }
      }
 
      // Utility function to create a new node
      /* Helper function that allocates a new node */
      function newNode(data) {
        var node = new Node();
        node.data = data;
        node.left = node.right = null;
        return node;
      }
 
      /* Recursive function to construct binary of size n
      from Inorder traversal in[] and Postorder traversal
      post[]. Initial values of inStrt and inEnd should
      be 0 and n -1. The function doesn't do any error
      checking for cases where inorder and postorder
      do not form a tree */
      function buildUtil(init, post, inStrt, inEnd) {
        // Base case
        if (inStrt > inEnd) {
          return null;
        }
 
        /* Pick current node from Postorder traversal
          using postIndex and decrement postIndex */
        var curr = post[index];
        var node = newNode(curr);
        index--;
 
        /* If this node has no children then return */
        if (inStrt == inEnd) {
          return node;
        }
 
        /* Else find the index of this node in Inorder
          traversal */
        var iIndex = mp[curr];
 
        /* Using index in Inorder traversal, con
          left and right subtrees */
        node.right = buildUtil(init, post, iIndex + 1, inEnd);
        node.left = buildUtil(init, post, inStrt, iIndex - 1);
        return node;
      }
      var mp = {};
      var index;
 
      // This function mainly creates an unordered_map, then
      // calls buildTreeUtil()
      function buildTree(init, post, len) {
        // Store indexes of all items so that we
        // we can quickly find later
        for (var i = 0; i < len; i++) {
          mp[init[i]] = i;
        }
 
        index = len - 1; // Index in postorder
        return buildUtil(init, post, 0, len - 1);
      }
 
      /* This function is here just to test */
      function preOrder(node) {
        if (node == null) {
          return;
        }
        document.write(node.data + " ");
        preOrder(node.left);
        preOrder(node.right);
      }
 
      // Driver code
      var init = [4, 8, 2, 5, 1, 6, 3, 7];
      var post = [8, 4, 5, 2, 6, 7, 3, 1];
      var n = init.length;
      var root = buildTree(init, post, n);
      document.write("Preorder of the constructed tree : <br>");
      preOrder(root);
       
</script>


Output

Preorder of the constructed tree : 
1 2 4 8 5 3 6 7

Time Complexity: O(N) 
Auxiliary Space: O(N), The extra space is used due to the recursion call stack and to store the elements in the map.

Construct a Binary Tree from Postorder and Inorder using stack and set:

We can use the stack and set without using recursion.

Follow the below steps to solve the problem:

  • Create a stack and a set of type Node* and initialize an integer postIndex with N-1
  • Run a for loop with p and i, from n-1 to 0
    • Create a new Node with value as postorder[p] and set it as the root node, if it is the first node of our newly created tree
    • Check if the value of stack top is already present in the set, then remove it from the set and set the left child of stack top equal to the new node and pop out the stack top
    • Push the current node into the stack
    • Perform step numbers 3,4 and 5 while p is greater than or equal to zero and postorder[p] is not equal to inorder[i]
    • Set the new node equal to null and while the stack’s top data is equal to the inorder[i], set the node equal to stack top and pop out the stack top
    • If the node is not null then insert the node into the set and push it into the stack also
  • Return root of the newly created tree

Below is the implementation of the above idea:

C++




// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree node has data, pointer
to left   child and a pointer to right
child */
struct Node {
    int data;
    Node *left, *right;
    Node(int x)
    {
        data = x;
        left = right = NULL;
    }
};
 
/*Tree building function*/
Node* buildTree(int in[], int post[], int n)
{
 
    // Create Stack of type Node*
    stack<Node*> st;
 
    // Create Set of type Node*
    set<Node*> s;
 
    // Initialise postIndex with n - 1
    int postIndex = n - 1;
 
    // Initialise root with NULL
    Node* root = NULL;
 
    for (int p = n - 1, i = n - 1; p >= 0;) {
 
        // Initialise node with NULL
        Node* node = NULL;
 
        // Run do-while loop
        do {
 
            // Initialise node with
            // new Node(post[p]);
            node = new Node(post[p]);
 
            // Check is root is
            // equal to NULL
            if (root == NULL) {
                root = node;
            }
 
            // If size of set
            // is greater than 0
            if (st.size() > 0) {
 
                // If st.top() is present in the
                // set s
                if (s.find(st.top()) != s.end()) {
                    s.erase(st.top());
                    st.top()->left = node;
                    st.pop();
                }
                else {
                    st.top()->right = node;
                }
            }
 
            st.push(node);
 
        } while (post[p--] != in[i] && p >= 0);
 
        node = NULL;
 
        // If the stack is not empty and
        // st.top()->data is equal to in[i]
        while (st.size() > 0 && i >= 0
               && st.top()->data == in[i]) {
            node = st.top();
 
            // Pop elements from stack
            st.pop();
            i--;
        }
 
        // if node not equal to NULL
        if (node != NULL) {
            s.insert(node);
            st.push(node);
        }
    }
 
    // Return root
    return root;
}
/* for print preOrder Traversal */
void preOrder(Node* node)
{
    if (node == NULL)
        return;
    printf("%d ", node->data);
    preOrder(node->left);
    preOrder(node->right);
}
 
// Driver Code
int main()
{
 
    int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 };
    int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 };
    int n = sizeof(in) / sizeof(in[0]);
 
    // Function Call
    Node* root = buildTree(in, post, n);
 
    cout << "Preorder of the constructed tree : \n";
 
    // Function Call for preOrder
    preOrder(root);
    return 0;
}


Java




// Java program for above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Node class
    static class Node {
        int data;
        Node left, right;
 
        // Constructor
        Node(int x)
        {
            data = x;
            left = right = null;
        }
    }
 
    // Tree building function
    static Node buildTree(int in[], int post[], int n)
    {
 
        // Create Stack of type Node*
        Stack<Node> st = new Stack<>();
 
        // Create HashSet of type Node*
        HashSet<Node> s = new HashSet<>();
 
        // Initialise postIndex with n - 1
        int postIndex = n - 1;
 
        // Initialise root with null
        Node root = null;
 
        for (int p = n - 1, i = n - 1; p >= 0😉 {
 
            // Initialise node with NULL
            Node node = null;
 
            // Run do-while loop
            do {
 
                // Initialise node with
                // new Node(post[p]);
                node = new Node(post[p]);
 
                // Check is root is
                // equal to NULL
                if (root == null) {
                    root = node;
                }
 
                // If size of set
                // is greater than 0
                if (st.size() > 0) {
 
                    // If st.peek() is present in the
                    // set s
                    if (s.contains(st.peek())) {
                        s.remove(st.peek());
                        st.peek().left = node;
                        st.pop();
                    }
                    else {
                        st.peek().right = node;
                    }
                }
                st.push(node);
 
            } while (post[p--] != in[i] && p >= 0);
 
            node = null;
 
            // If the stack is not empty and
            // st.top().data is equal to in[i]
            while (st.size() > 0 && i >= 0
                   && st.peek().data == in[i]) {
                node = st.peek();
 
                // Pop elements from stack
                st.pop();
                i--;
            }
 
            // If node not equal to NULL
            if (node != null) {
                s.add(node);
                st.push(node);
            }
        }
 
        // Return root
        return root;
    }
 
    // For print preOrder Traversal
    static void preOrder(Node node)
    {
        if (node == null)
            return;
 
        System.out.printf("%d ", node.data);
        preOrder(node.left);
        preOrder(node.right);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 };
        int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 };
        int n = in.length;
 
        // Function Call
        Node root = buildTree(in, post, n);
 
        System.out.print(
            "Preorder of the constructed tree : \n");
 
        // Function Call for preOrder
        preOrder(root);
    }
}
 
// This code is contributed by sujitmeshram


Python3




# Python program for above approach
 
# A binary tree node has data, pointer
# to left   child and a pointer to right
# child
 
 
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None
 
# Tree building function
 
 
def buildTree(inorder, post, n):
    # Create Stack of type Node
    st = []
    # Create Set of type Node
    set = []
    # Initialise postIndex with n - 1
    postIndex = n - 1
    # Initialise root with NULL
    root = None
 
    p = n-1
    i = n-1
 
    while p >= 0:
        # Initialise node with NULL
        node = None
 
        #  Run loop
        while True:
 
            # initialize new node
            node = Node(post[p])
 
            # check if root is equal to null
            if root == None:
                root = node
 
            # If size of set is greater than 0
            if len(st) > 0:
 
                # If st top is present in the set s
                if st[-1] in set:
                    set.remove(st[-1])
                    st[-1].left = node
                    st.pop()
                else:
                    st[-1].right = node
 
            st.append(node)
 
            p -= 1
            if post[p+1] == inorder[i] or p < 0:
                break
 
        node = None
 
        # If the stack is not empty and st top data is equal to in[i]
        while len(st) > 0 and i >= 0 and st[-1].data == inorder[i]:
            node = st[-1]
            # Pop elements from stack
            st.pop()
            i -= 1
 
        # if node not equal to None
        if node != None:
            set.append(node)
            st.append(node)
 
    # Return root
    return root
 
#  for print preOrder Traversal
 
 
def preOrder(node):
    if node == None:
        return
    print(node.data, end=" ")
    preOrder(node.left)
    preOrder(node.right)
 
 
# Driver Code
if __name__ == '__main__':
    inorder = [4, 8, 2, 5, 1, 6, 3, 7]
    post = [8, 4, 5, 2, 6, 7, 3, 1]
    n = len(inorder)
 
    # Function Call
    root = buildTree(inorder, post, n)
 
    print("Preorder of the constructed tree :")
 
    # Function Call for preOrder
    preOrder(root)
 
# This code is contributed by Tapesh(tapeshdua420)


C#




// C# program for above approach
using System;
using System.Collections.Generic;
class GFG {
 
    // Node class
    public class Node {
        public int data;
        public Node left, right;
 
        // Constructor
        public Node(int x)
        {
            data = x;
            left = right = null;
        }
    }
 
    // Tree building function
    static Node buildTree(int[] init, int[] post, int n)
    {
 
        // Create Stack of type Node*
        Stack<Node> st = new Stack<Node>();
 
        // Create HashSet of type Node*
        HashSet<Node> s = new HashSet<Node>();
 
        // Initialise root with null
        Node root = null;
        for (int p = n - 1, i = n - 1; p >= 0;) {
 
            // Initialise node with NULL
            Node node = null;
 
            // Run do-while loop
            do {
 
                // Initialise node with
                // new Node(post[p]);
                node = new Node(post[p]);
 
                // Check is root is
                // equal to NULL
                if (root == null) {
                    root = node;
                }
 
                // If size of set
                // is greater than 0
                if (st.Count > 0) {
 
                    // If st.Peek() is present in the
                    // set s
                    if (s.Contains(st.Peek())) {
                        s.Remove(st.Peek());
                        st.Peek().left = node;
                        st.Pop();
                    }
                    else {
                        st.Peek().right = node;
                    }
                }
                st.Push(node);
 
            } while (post[p--] != init[i] && p >= 0);
 
            node = null;
 
            // If the stack is not empty and
            // st.top().data is equal to in[i]
            while (st.Count > 0 && i >= 0
                   && st.Peek().data == init[i]) {
                node = st.Peek();
 
                // Pop elements from stack
                st.Pop();
                i--;
            }
 
            // If node not equal to NULL
            if (node != null) {
                s.Add(node);
                st.Push(node);
            }
        }
 
        // Return root
        return root;
    }
 
    // For print preOrder Traversal
    static void preOrder(Node node)
    {
        if (node == null)
            return;
 
        Console.Write(node.data + " ");
        preOrder(node.left);
        preOrder(node.right);
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] init = { 4, 8, 2, 5, 1, 6, 3, 7 };
        int[] post = { 8, 4, 5, 2, 6, 7, 3, 1 };
        int n = init.Length;
 
        // Function Call
        Node root = buildTree(init, post, n);
        Console.Write(
            "Preorder of the constructed tree : \n");
 
        // Function Call for preOrder
        preOrder(root);
    }
}
 
// This code is contributed by aashish1995


Javascript




// JavaScript program for above approach
 
// Node class
class Node {
  constructor(data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}
 
// Tree building function
function buildTree(inorder, postorder, n) {
  // Create Stack of type Node
  let st = [];
 
  // Create Set of type Node
  let s = new Set();
 
  // Initialize postIndex with n - 1
  let postIndex = n - 1;
 
  // Initialize root with null
  let root = null;
 
  for (let p = n - 1, i = n - 1; p >= 0; ) {
    // Initialize node with null
    let node = null;
 
    do {
      // Initialize node with new Node(post[p]);
      node = new Node(postorder[p]);
 
      // Check if root is equal to null
      if (root === null) {
        root = node;
      }
 
      // If size of set is greater than 0
      if (st.length > 0)
      {
       
        // If st[st.length - 1] is present in the set s
        if (s.has(st[st.length - 1])) {
          s.delete(st[st.length - 1]);
          st[st.length - 1].left = node;
          st.pop();
        } else {
          st[st.length - 1].right = node;
        }
      }
      st.push(node);
    } while (postorder[p--] !== inorder[i] && p >= 0);
 
    node = null;
 
    // If the stack is not empty and
    // st[st.length - 1].data is equal to in[i]
    while (
      st.length > 0 &&
      i >= 0 &&
      st[st.length - 1].data === inorder[i]
    ) {
      node = st[st.length - 1];
 
      // Pop elements from stack
      st.pop();
      i--;
    }
 
    // If node not equal to null
    if (node !== null) {
      s.add(node);
      st.push(node);
    }
  }
 
  // Return root
  return root;
}
 
// For print preOrder Traversal
function preOrder(node) {
  if (node === null) return;
 
  console.log(node.data + " ");
  preOrder(node.left);
  preOrder(node.right);
}
 
// Test
const inorder = [4, 8, 2, 5, 1, 6, 3, 7];
const postorder = [8, 4, 5, 2, 6, 7, 3, 1];
const n = inorder.length;
 
// Function Call
const root = buildTree(inorder, postorder, n);
 
console.log("Preorder of the constructed tree: ");
 
// Function Call for preOrder
preOrder(root);
 
// This code is contributed by lokesh.


Output

Preorder of the constructed tree : 
1 2 4 8 5 3 6 7

Time Complexity: O(N)
Auxiliary Space: O(N), The extra space is used to store the elements in the stack and set.



Similar Reads

Preorder, Postorder and Inorder Traversal of a Binary Tree using a single Stack
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order iteratively using only one stack traversal. Examples: Input: Output:Preorder Traversal: 1 2 3Inorder Traversal: 2 1 3Postorder Traversal: 2 3 1 Input: Output:Preorder traversal: 1 2 4 5 3 6 7Inorder traversal: 4 2 5 1 6 3 7Post-order tr
13 min read
Check if given Preorder, Inorder and Postorder traversals are of same tree
Given Preorder, Inorder, and Postorder traversals of some tree. Write a program to check if they all are of the same tree. Examples: Input: Inorder -&gt; 4 2 5 1 3 Preorder -&gt; 1 2 4 5 3 Postorder -&gt; 4 5 2 3 1Output: YesExplanation: All of the above three traversals are of the same tree 1 / \ 2 3 / \ 4 5Input: Inorder -&gt; 4 2 5 1 3 Preorder
15+ min read
Construct Full Binary Tree from given preorder and postorder traversals
Given two arrays that represent preorder and postorder traversals of a full binary tree, construct the binary tree. Full Binary Tree is a binary tree where every node has either 0 or 2 children. Illustration: Following are examples of Full Trees. 1 / \ 2 3 / \ / \ 4 5 6 7 1 / \ 2 3 / \ 4 5 / \ 6 7 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 It is not possibl
14 min read
Construct a Binary Search Tree from given postorder
Given postorder traversal of a binary search tree, construct the BST. For example, if the given traversal is {1, 7, 5, 50, 40, 10}, then following tree should be constructed and root of the tree should be returned. 10 / \ 5 40 / \ \ 1 7 50Recommended PracticeConstruct BST from PostorderTry It! Method 1 ( O(n^2) time complexity ): The last element o
13 min read
Construct Special Binary Tree from given Inorder traversal
Given Inorder Traversal of a Special Binary Tree in which the key of every node is greater than keys in left and right children, construct the Binary Tree and return root. Examples: Input: inorder[] = {5, 10, 40, 30, 28} Output: root of following tree 40 / \ 10 30 / \ 5 28 Input: inorder[] = {1, 5, 10, 40, 30, 15, 28, 20} Output: root of following
14 min read
Print Postorder traversal from given Inorder and Preorder traversals
AuxiliaryGiven Inorder and Preorder traversals of a binary tree, print Postorder traversal. Example: Input: Inorder traversal in[] = {4, 2, 5, 1, 3, 6} Preorder traversal pre[] = {1, 2, 4, 5, 3, 6} Output: Postorder traversal is {4, 5, 2, 6, 3, 1} Traversals in the above example represents following tree 1 / \ 2 3 / \ \ 4 5 6Recommended PracticePos
15+ min read
Preorder from Inorder and Postorder traversals
Given Inorder and Postorder traversals of a binary tree, print Preorder traversal. Example: Input: Postorder traversal post[] = {4, 5, 2, 6, 3, 1} Inorder traversal in[] = {4, 2, 5, 1, 3, 6} Output: Preorder traversal 1, 2, 4, 5, 3, 6 Traversals in the above example represents following tree 1 / \ 2 3 / \ \ 4 5 6Recommended: Please solve it on “PRA
15 min read
Preorder vs Inorder vs Postorder
In Preorder Traversal, the root node is visited first, followed by the left and right subtrees. Inorder Traversal starts with the left subtree, visits the root, and then the right subtree, often used in binary search trees. Postorder Traversal begins with the left subtree, moves to the right subtree, and visits the root last, useful for deleting no
7 min read
Construct a Complete N-ary Tree from given Postorder Traversal
Given an array arr[] of size M that contains the post-order traversal of a complete N-ary tree, the task is to generate the N-ary tree and print its preorder traversal. A complete tree is a tree where all the levels of the tree are completely filled, except may be for the last level but the nodes in the last level are as left as possible. Examples:
13 min read
Construct a tree from Inorder and Level order traversals | Set 1
Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree. Following is an example to illustrate the problem. Input: Two arrays that represent Inorder and level order traversals of a Binary Tree in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14}; Output: Construct the tree represented by the two array
11 min read
Construct a tree from Inorder and Level order traversals | Set 2
Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree. Following is an example to illustrate the problem. Examples: Input: Two arrays that represent Inorder and level order traversals of a Binary Tree in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14}; Output: Construct the tree represented by the
15+ min read
Construct Tree from given Inorder and Preorder traversals
Let us consider the below traversals: Inorder sequence: D B E A F C Preorder sequence: A B D E C FIn a Preorder sequence, the leftmost element is the root of the tree. So we know 'A' is the root for given sequences. By searching ‘A’ in the Inorder sequence, we can find out all elements on the left side of 'A' is in the left subtree and elements on
15+ min read
Check if given inorder and preorder traversals are valid for any Binary Tree without building the tree
cGiven two arrays pre[] and in[] representing the preorder and inorder traversal of the binary tree, the task is to check if the given traversals are valid for any binary tree or not without building the tree. If it is possible, then print Yes. Otherwise, print No. Examples: Input: pre[] = {1, 2, 4, 5, 7, 3, 6, 8}, in[] = {4, 2, 5, 7, 1, 6, 8, 3}Ou
15+ min read
Construct a BST from given postorder traversal using Stack
Given postorder traversal of a binary search tree, construct the BST.For example, If the given traversal is {1, 7, 5, 50, 40, 10}, then following tree should be constructed and root of the tree should be returned. 10 / \ 5 40 / \ \ 1 7 50 Input : 1 7 5 50 40 10 Output : Inorder traversal of the constructed tree: 1 5 7 10 40 50 If the given traversa
9 min read
Postorder traversal of Binary Tree without recursion and without stack
Given a binary tree, perform postorder traversal. Prerequisite - Inorder/preorder/postorder traversal of tree We have discussed the below methods for postorder traversal. 1) Recursive Postorder Traversal. 2) Postorder traversal using Stack. 2) Postorder traversal using two Stacks. Approach 1 The approach used is based on using an unordered set to k
15 min read
Postorder successor of a Node in Binary Tree
Given a binary tree and a node in the binary tree, find Postorder successor of the given node. Examples: Consider the following binary tree 20 / \ 10 26 / \ / \ 4 18 24 27 / \ 14 19 / \ 13 15 Postorder traversal of given tree is 4, 13, 15, 14, 19, 18, 10, 24, 27, 26, 20. Input : Complexity Analysis:24 Output : 27 Input : 4 Output : 13 A simple solu
8 min read
Postorder predecessor of a Node in Binary Search Tree
Given a binary tree and a node in the binary tree, find the Postorder predecessor of the given node. Examples: Consider the following binary tree 20 / \ 10 26 / \ / \ 4 18 24 27 / \ 14 19 / \ 13 15 Input : 4 Output : 10 Postorder traversal of given tree is 4, 13, 15, 14, 19, 18, 10, 24, 27, 26, 20. Input : 24 Output : 10 A simple solution is to fir
8 min read
Find n-th node in Postorder traversal of a Binary Tree
Given a Binary tree and a number N, write a program to find the N-th node in the Postorder traversal of the given Binary tree. Prerequisite: Tree Traversal Examples: Input : N = 4 11 / \ 21 31 / \ 41 51 Output : 31 Explanation: Postorder Traversal of given Binary Tree is 41 51 21 31 11, so 4th node will be 31. Input : N = 5 25 / \ 20 30 / \ / \ 18
13 min read
Find parent of given node in a Binary Tree with given postorder traversal
Given two integers N and K where N denotes the height of a binary tree, the task is to find the parent of the node with value K in a binary tree whose postorder traversal is first [Tex]2^{N}-1 [/Tex] natural numbers [Tex](1, 2, ... 2^{N}-1) [/Tex] For N = 3, the Tree will be - 7 / \ 3 6 / \ / \ 1 2 4 5 Examples: Input: N = 4, K = 5 Output: 6 Explan
9 min read
Postorder Traversal of Binary Tree
Postorder traversal is defined as a type of tree traversal which follows the Left-Right-Root policy such that for each node: The left subtree is traversed firstThen the right subtree is traversedFinally, the root node of the subtree is traversed Algorithm for Postorder Traversal of Binary Tree:The algorithm for postorder traversal is shown as follo
6 min read
Calculate height of Binary Tree using Inorder and Level Order Traversal
Given inorder traversal and Level Order traversal of a Binary Tree. The task is to calculate the height of the tree without constructing it. Example: Input : Input: Two arrays that represent Inorder and level order traversals of a Binary Tree in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14}; Output : 4 The binary tree that ca
12 min read
Replace each node in binary tree with the sum of its inorder predecessor and successor
Given a binary tree containing n nodes. The problem is to replace each node in the binary tree with the sum of its inorder predecessor and inorder successor. Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 11 / \ 9 13 / \ / \ 2 3 4 3 For 1: Inorder predecessor = 5 Inorder successor = 6 Sum = 11 For 4: Inorder predecessor = 0 (as inorder predec
15+ min read
Cartesian tree from inorder traversal | Segment Tree
Given an in-order traversal of a cartesian tree, the task is to build the entire tree from it. Examples: Input: arr[] = {1, 5, 3} Output: 1 5 3 5 / \ 1 3 Input: arr[] = {3, 7, 4, 8} Output: 3 7 4 8 8 / 7 / \ 3 4 Approach: We have already seen an algorithm here that takes O(NlogN) time on an average but can get to O(N2) in the worst case.In this art
13 min read
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, we need to write a program to construct the binary tree using these two Preorder traversals.A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a general binary tree using these two traver
12 min read
Print K inorder successors of a Binary Tree in O(1) space
Given a Binary Tree and two numbers P and K, the task is to print the K Inorder Successor of the given number P from the Binary tree in constant space.Examples: Input: Tree: 1 / \ 12 11 / / \ 3 4 13 \ / 15 9 P = 12, K = 4 Output: 1 4 15 11 Explanation: Inorder traversal: 3 12 1 4 15 11 9 13 The 4 Inorder Successor of a node 12 are {1, 4, 15, 11} In
10 min read
Check if Inorder traversal of a Binary Tree is palindrome or not
Given a binary tree and the task if to check if its Inorder Sequence is a palindrome or not. Examples: Input: Output: True Explanation: The Inorder sequence of the tree is "bbaaabb" which is a palindromic string.Input: Output: False Explanation: The Inorder sequence of the tree is "bbdaabb" which is not a palindromic string. Approach: To solve the
8 min read
Binary Tree Iterator for Inorder Traversal
Given a Binary Tree and an input array. The task is to create an Iterator that utilizes next() and hasNext() functions to perform Inorder traversal on the binary tree. Examples: Input: 8 Input Array = [next(), hasNext(), next(), next(), next(), hasNext(), next(), next(), hasNext()] / \ 3 9 / \ 2 4 \ 5 Output: [2, true, 3, 4, 5, true, 8, 9, false] E
13 min read
Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
We have discussed Thread based Morris Traversal. Can we do inorder traversal without threads if we have parent pointers available to us? Input: Root of Below Tree [Every node of tree has parent pointer also] 10 / \ 5 100 / \ 80 120 Output: 5 10 80 100 120 The code should not extra space (No Recursion and stack) In inorder traversal, we follow "left
11 min read
Check if an array represents Inorder of Binary Search tree or not
Given an array of N element. The task is to check if it is Inorder traversal of any Binary Search Tree or not. Print "Yes" if it is Inorder traversal of any Binary Search Tree else print "No". Examples: Input : arr[] = { 19, 23, 25, 30, 45 } Output : Yes Input : arr[] = { 19, 23, 30, 25, 45 } Output : NoRecommended PracticeInorder Traversal and BST
5 min read
Convert Binary Tree to Doubly Linked List using inorder traversal
Given a Binary Tree (Bt), convert it to a Doubly Linked List(DLL). The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as in Inorder for the given Binary Tree. The first node of Inorder traversal (leftmost node in BT) must be the head node of the
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg