The Wayback Machine - https://web.archive.org/web/20240826235720/https://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-preorder-traversal/
Open In App

Construct Tree from given Inorder and Preorder traversals

Last Updated : 12 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Medium
34.59%
1.7L

Let us consider the below traversals:

  • Inorder sequence: D B E A F C 
  • Preorder sequence: A B D E C F

In 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 right in the right subtree. So we know the below structure now. 

                 A
/ \
/ \
D B E F C


We recursively follow the above steps and get the following tree.

         A
/ \
/ \
B C
/ \ /
/ \ /
D E F


Algorithm: buildTree() 

  1. Pick an element from Preorder. Increment a Preorder Index Variable (preIndex in below code) to pick the next element in the next recursive call. 
  2. Create a new tree node tNode with the data as the picked element. 
  3. Find the picked element’s index in Inorder. Let the index be inIndex. 
  4. Call buildTree for elements before inIndex and make the built tree as a left subtree of tNode. 
  5. Call buildTree for elements after inIndex and make the built tree as a right subtree of tNode. 
  6. return tNode.
C++
/* C++ program to construct tree using 
inorder and preorder traversals */
#include <bits/stdc++.h>
using namespace std;

/* A binary tree node has data, pointer to left child 
and a pointer to right child */
class node 
{ 
    public:
    char data; 
    node* left; 
    node* right; 
}; 

/* Prototypes for utility functions */
int search(char arr[], int strt, int end, char value); 
node* newNode(char data); 

/* Recursive function to construct binary
of size len from Inorder traversal in[] 
and Preorder traversal pre[]. Initial values 
of inStrt and inEnd should be 0 and len -1. 
The function doesn't do any error checking 
for cases where inorder and preorder do not
form a tree */
node* buildTree(char in[], char pre[], int inStrt, int inEnd) 
{ 
    static int preIndex = 0; 

    if (inStrt > inEnd) 
        return NULL; 

    /* Pick current node from Preorder
    traversal using preIndex 
    and increment preIndex */
    node* tNode = newNode(pre[preIndex++]); 

    /* If this node has no children then return */
    if (inStrt == inEnd) 
        return tNode; 

    /* Else find the index of this node in Inorder traversal */
    int inIndex = search(in, inStrt, inEnd, tNode->data); 

    /* Using index in Inorder traversal, construct left and 
    right subtress */
    tNode->left = buildTree(in, pre, inStrt, inIndex - 1); 
    tNode->right = buildTree(in, pre, inIndex + 1, inEnd); 

    return tNode; 
} 

/* UTILITY FUNCTIONS */
/* Function to find index of value in arr[start...end] 
The function assumes that value is present in in[] */
int search(char arr[], int strt, int end, char value) 
{ 
    int i; 
    for (i = strt; i <= end; i++) 
    { 
        if (arr[i] == value) 
            return i; 
    } 
} 

/* Helper function that allocates a new node with the 
given data and NULL left and right pointers. */
node* newNode(char data) 
{ 
    node* Node = new node();
    Node->data = data; 
    Node->left = NULL; 
    Node->right = NULL; 

    return (Node); 
} 

/* This function is here just to test buildTree() */
void printInorder(node* node) 
{ 
    if (node == NULL) 
        return; 

    /* first recur on left child */
    printInorder(node->left); 

    /* then print the data of node */
    cout<<node->data<<" "; 

    /* now recur on right child */
    printInorder(node->right); 
} 

/* Driver code */
int main() 
{ 
    char in[] = { 'D', 'B', 'E', 'A', 'F', 'C' }; 
    char pre[] = { 'A', 'B', 'D', 'E', 'C', 'F' }; 
    int len = sizeof(in) / sizeof(in[0]); 
    node* root = buildTree(in, pre, 0, len - 1); 

    /* Let us test the built tree by 
    printing Inorder traversal */
    cout << "Inorder traversal of the constructed tree is \n"; 
    printInorder(root); 
} 

// This is code is contributed by rathbhupendra
C
/* program to construct tree using inorder and preorder traversals */
#include <stdio.h>
#include <stdlib.h>

/* A binary tree node has data, pointer to left child
   and a pointer to right child */
struct node {
    char data;
    struct node* left;
    struct node* right;
};

/* Prototypes for utility functions */
int search(char arr[], int strt, int end, char value);
struct node* newNode(char data);

/* Recursive function to construct binary of size len from
   Inorder traversal in[] and Preorder traversal pre[].  Initial values
   of inStrt and inEnd should be 0 and len -1.  The function doesn't
   do any error checking for cases where inorder and preorder
   do not form a tree */
struct node* buildTree(char in[], char pre[], int inStrt, int inEnd)
{
    static int preIndex = 0;

    if (inStrt > inEnd)
        return NULL;

    /* Pick current node from Preorder traversal using preIndex
    and increment preIndex */
    struct node* tNode = newNode(pre[preIndex++]);

    /* If this node has no children then return */
    if (inStrt == inEnd)
        return tNode;

    /* Else find the index of this node in Inorder traversal */
    int inIndex = search(in, inStrt, inEnd, tNode->data);

    /* Using index in Inorder traversal, construct left and
     right subtress */
    tNode->left = buildTree(in, pre, inStrt, inIndex - 1);
    tNode->right = buildTree(in, pre, inIndex + 1, inEnd);

    return tNode;
}

/* UTILITY FUNCTIONS */
/* Function to find index of value in arr[start...end]
   The function assumes that value is present in in[] */
int search(char arr[], int strt, int end, char value)
{
    int i;
    for (i = strt; i <= end; i++) {
        if (arr[i] == value)
            return i;
    }
}

/* Helper function that allocates a new node with the
   given data and NULL left and right pointers. */
struct node* newNode(char data)
{
    struct node* node = (struct node*)malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;

    return (node);
}

/* This function is here just to test buildTree() */
void printInorder(struct node* node)
{
    if (node == NULL)
        return;

    /* first recur on left child */
    printInorder(node->left);

    /* then print the data of node */
    printf("%c ", node->data);

    /* now recur on right child */
    printInorder(node->right);
}

/* Driver program to test above functions */
int main()
{
    char in[] = { 'D', 'B', 'E', 'A', 'F', 'C' };
    char pre[] = { 'A', 'B', 'D', 'E', 'C', 'F' };
    int len = sizeof(in) / sizeof(in[0]);
    struct node* root = buildTree(in, pre, 0, len - 1);

    /* Let us test the built tree by printing Inorder traversal */
    printf("Inorder traversal of the constructed tree is \n");
    printInorder(root);
    getchar();
}
Java
// Java program to construct a tree using inorder and preorder traversal

/* A binary tree node has data, pointer to left child
   and a pointer to right child */
class Node {
    char data;
    Node left, right;

    Node(char item)
    {
        data = item;
        left = right = null;
    }
}

class BinaryTree {
    Node root;
    static int preIndex = 0;

    /* Recursive function to construct binary of size len from
       Inorder traversal in[] and Preorder traversal pre[].
       Initial values of inStrt and inEnd should be 0 and len -1.  
       The function doesn't do any error checking for cases where 
       inorder and preorder do not form a tree */
    Node buildTree(char in[], char pre[], int inStrt, int inEnd)
    {
        if (inStrt > inEnd)
            return null;

        /* Pick current node from Preorder traversal using preIndex
           and increment preIndex */
        Node tNode = new Node(pre[preIndex++]);

        /* If this node has no children then return */
        if (inStrt == inEnd)
            return tNode;

        /* Else find the index of this node in Inorder traversal */
        int inIndex = search(in, inStrt, inEnd, tNode.data);

        /* Using index in Inorder traversal, construct left and
           right subtress */
        tNode.left = buildTree(in, pre, inStrt, inIndex - 1);
        tNode.right = buildTree(in, pre, inIndex + 1, inEnd);

        return tNode;
    }

    /* UTILITY FUNCTIONS */

    /* Function to find index of value in arr[start...end]
     The function assumes that value is present in in[] */
    int search(char arr[], int strt, int end, char value)
    {
        int i;
        for (i = strt; i <= end; i++) {
            if (arr[i] == value)
                return i;
        }
        return i;
    }

    /* This function is here just to test buildTree() */
    void printInorder(Node node)
    {
        if (node == null)
            return;

        /* first recur on left child */
        printInorder(node.left);

        /* then print the data of node */
        System.out.print(node.data + " ");

        /* now recur on right child */
        printInorder(node.right);
    }

    // driver program to test above functions
    public static void main(String args[])
    {
        BinaryTree tree = new BinaryTree();
        char in[] = new char[] { 'D', 'B', 'E', 'A', 'F', 'C' };
        char pre[] = new char[] { 'A', 'B', 'D', 'E', 'C', 'F' };
        int len = in.length;
        Node root = tree.buildTree(in, pre, 0, len - 1);

        // building the tree by printing inorder traversal
        System.out.println("Inorder traversal of constructed tree is : ");
        tree.printInorder(root);
    }
}

// This code has been contributed by Mayank Jaiswal
Python
# Python program to construct tree using inorder and 
# preorder traversals

# A binary tree node 
class Node:
    
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

"""Recursive function to construct binary of size len from
   Inorder traversal in[] and Preorder traversal pre[].  Initial values
   of inStrt and inEnd should be 0 and len -1.  The function doesn't
   do any error checking for cases where inorder and preorder
   do not form a tree """
def buildTree(inOrder, preOrder, inStrt, inEnd):
    
    if (inStrt > inEnd):
        return None

    # Pick current node from Preorder traversal using
    # preIndex and increment preIndex
    tNode = Node(preOrder[buildTree.preIndex])
    buildTree.preIndex += 1

    # If this node has no children then return
    if inStrt == inEnd :
        return tNode

    # Else find the index of this node in Inorder traversal
    inIndex = search(inOrder, inStrt, inEnd, tNode.data)
    
    # Using index in Inorder Traversal, construct left 
    # and right subtrees
    tNode.left = buildTree(inOrder, preOrder, inStrt, inIndex-1)
    tNode.right = buildTree(inOrder, preOrder, inIndex + 1, inEnd)

    return tNode

# UTILITY FUNCTIONS
# Function to find index of value in arr[start...end]
# The function assumes that value is present in inOrder[]

def search(arr, start, end, value):
    for i in range(start, end + 1):
        if arr[i] == value:
            return i

def printInorder(node):
    if node is None:
        return 
    
    # first recur on left child
    printInorder(node.left)
    
    # then print the data of node
    print (node.data,end=' ')

    # now recur on right child
    printInorder(node.right)
    
# Driver program to test above function
inOrder = ['D', 'B', 'E', 'A', 'F', 'C']
preOrder = ['A', 'B', 'D', 'E', 'C', 'F']
# Static variable preIndex
buildTree.preIndex = 0
root = buildTree(inOrder, preOrder, 0, len(inOrder)-1)

# Let us test the build tree by printing Inorder traversal
print ("Inorder traversal of the constructed tree is")
printInorder(root)

# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
// C# program to construct a tree using
// inorder and preorder traversal
using System;

/* A binary tree node has data, pointer 
to left child and a pointer to right child */
public class Node {
    public char data;
    public Node left, right;

    public Node(char item)
    {
        data = item;
        left = right = null;
    }
}

class GFG {
    public Node root;
    public static int preIndex = 0;

    /* Recursive function to construct binary 
of size len from Inorder traversal in[] 
and Preorder traversal pre[]. Initial values 
of inStrt and inEnd should be 0 and len -1. 
The function doesn't do any error checking for 
cases where inorder and preorder do not form a tree */
    public virtual Node buildTree(char[] arr, char[] pre,
                                  int inStrt, int inEnd)
    {
        if (inStrt > inEnd) {
            return null;
        }

        /* Pick current node from Preorder traversal
     using preIndex and increment preIndex */
        Node tNode = new Node(pre[preIndex++]);

        /* If this node has no children then return */
        if (inStrt == inEnd) {
            return tNode;
        }

        /* Else find the index of this
       node in Inorder traversal */
        int inIndex = search(arr, inStrt,
                             inEnd, tNode.data);

        /* Using index in Inorder traversal, 
    construct left and right subtress */
        tNode.left = buildTree(arr, pre, inStrt, inIndex - 1);
        tNode.right = buildTree(arr, pre, inIndex + 1, inEnd);

        return tNode;
    }

    /* UTILITY FUNCTIONS */

    /* Function to find index of value in arr[start...end] 
The function assumes that value is present in in[] */
    public virtual int search(char[] arr, int strt,
                              int end, char value)
    {
        int i;
        for (i = strt; i <= end; i++) {
            if (arr[i] == value) {
                return i;
            }
        }
        return i;
    }

    /* This function is here just to test buildTree() */
    public virtual void printInorder(Node node)
    {
        if (node == null) {
            return;
        }

        /* first recur on left child */
        printInorder(node.left);

        /* then print the data of node */
        Console.Write(node.data + " ");

        /* now recur on right child */
        printInorder(node.right);
    }

    // Driver Code
    public static void Main(string[] args)
    {
        GFG tree = new GFG();
        char[] arr = new char[] { 'D', 'B', 'E', 'A', 'F', 'C' };
        char[] pre = new char[] { 'A', 'B', 'D', 'E', 'C', 'F' };
        int len = arr.Length;
        Node root = tree.buildTree(arr, pre, 0, len - 1);

        // building the tree by printing inorder traversal
        Console.WriteLine("Inorder traversal of "
                          + "constructed tree is : ");
        tree.printInorder(root);
    }
}

// This code is contributed by Shrikant13
JavaScript
<script>

// Javascript program to construct a 
// tree using inorder and preorder traversal
 
// A binary tree node has data, pointer
// to left child and a pointer to right child 
class Node
{
    constructor(item)
    {
        this.data = item;
        this.left = this.right = null;
    }
}

let root;
let preIndex = 0;

// Recursive function to construct binary
// of size len from Inorder traversal in[] 
// and Preorder traversal pre[]. Initial 
// values of inStrt and inEnd should be 0 
// and len -1. The function doesn't do any 
// error checking for cases where inorder 
// and preorder do not form a tree
function buildTree(In, pre, inStrt, inEnd)
{
    if (inStrt > inEnd)
        return null;

    // Pick current node from Preorder 
    // traversal using preIndex and 
    // increment preIndex 
    let tNode = new Node(pre[preIndex++]);

    // If this node has no children then return 
    if (inStrt == inEnd)
        return tNode;

    // Else find the index of this 
    // node in Inorder traversal 
    let inIndex = search(In, inStrt, 
                         inEnd, tNode.data);

    // Using index in Inorder traversal,
    // construct left and right subtress 
    tNode.left = buildTree(In, pre, inStrt,
                           inIndex - 1);
    tNode.right = buildTree(In, pre, 
                            inIndex + 1, 
                            inEnd);

    return tNode;
}

/* UTILITY FUNCTIONS */
 
// Function to find index of value 
// in arr[start...end]. The function 
// assumes that value is present in in[] 
function search(arr, strt, end, value)
{
    let i;
    for(i = strt; i <= end; i++) 
    {
        if (arr[i] == value)
            return i;
    }
    return i;
}

// This function is here just
// to test buildTree() 
function printInorder(node)
{
    if (node == null)
            return;
 
    // First recur on left child 
    printInorder(node.left);

    // Then print the data of node
    document.write(node.data + " ");

    // Now recur on right child 
    printInorder(node.right);
}

// Driver code
let In = [ 'D', 'B', 'E', 'A', 'F', 'C' ];
let pre = [ 'A', 'B', 'D', 'E', 'C', 'F'];
let len = In.length;
root = buildTree(In, pre, 0, len - 1);

// Building the tree by printing
// inorder traversal
document.write("Inorder traversal of " +
               "constructed tree is : <br>");
printInorder(root);

// This code is contributed by patel2127

</script>

Output
Inorder traversal of the constructed tree is 
D B E A F C 

Time Complexity: O(n^2), The worst case occurs when the tree is left-skewed. Example Preorder and Inorder traversals for worst-case are {A, B, C, D} and {D, C, B, A}. 
Auxiliary Space: O(n), The extra space used is due to the recursive call stack and the worst case occurs for a skewed tree.

Efficient Approach : 

We can optimize the above solution using hashing (unordered_map in C++ or HashMap in Java). We store indexes of inorder traversal in a hash table. So that search can be done O(1) time. 

C++
/* C++ program to construct tree using inorder
   and preorder 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 {
    char data;
    struct Node* left;
    struct Node* right;
};

struct Node* newNode(char data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}

/* Recursive function to construct binary of size
len from Inorder traversal in[] and Preorder traversal 
pre[]. Initial values of inStrt and inEnd should be 
0 and len -1. The function doesn't do any error 
checking for cases where inorder and preorder 
do not form a tree */
struct Node* buildTree(char in[], char pre[], int inStrt,
                       int inEnd, unordered_map<char, int>& mp)
{
    static int preIndex = 0;

    if (inStrt > inEnd)
        return NULL;

    /* Pick current node from Preorder traversal using preIndex 
    and increment preIndex */
    char curr = pre[preIndex++];
    struct Node* tNode = newNode(curr);

    /* If this node has no children then return */
    if (inStrt == inEnd)
        return tNode;

    /* Else find the index of this node in Inorder traversal */
    int inIndex = mp[curr];

    /* Using index in Inorder traversal, construct left and 
    right subtress */
    tNode->left = buildTree(in, pre, inStrt, inIndex - 1, mp);
    tNode->right = buildTree(in, pre, inIndex + 1, inEnd, mp);

    return tNode;
}

// This function mainly creates an unordered_map, then
// calls buildTree()
struct Node* buldTreeWrap(char in[], char pre[], int len)
{
    // Store indexes of all items so that we
    // we can quickly find later
    unordered_map<char, int> mp;
    for (int i = 0; i < len; i++)
        mp[in[i]] = i;

    return buildTree(in, pre, 0, len - 1, mp);
}

/* This function is here just to test buildTree() */
void printInorder(struct Node* node)
{
    if (node == NULL)
        return;
    printInorder(node->left);
    printf("%c ", node->data);
    printInorder(node->right);
}

/* Driver program to test above functions */
int main()
{
    char in[] = { 'D', 'B', 'E', 'A', 'F', 'C' };
    char pre[] = { 'A', 'B', 'D', 'E', 'C', 'F' };
    int len = sizeof(in) / sizeof(in[0]);

    struct Node* root = buldTreeWrap(in, pre, len);

    /* Let us test the built tree by printing 
      Inorder traversal */
    printf("Inorder traversal of the constructed tree is \n");
    printInorder(root);
}
Java
/* Java program to construct tree using inorder
   and preorder traversals */
import java.io.*;
import java.util.*; 

/* A binary tree node has data, pointer to left child 
and a pointer to right child */
class Node
{
  char data;
  Node left,right;
  Node(char item)
  {
    data = item;
    left = right = null;
  }
}
class Tree
{

  public static Node root;

  // Store indexes of all items so that we
  // we can quickly find later
  static HashMap<Character,Integer> mp = new HashMap<>();
  static int preIndex = 0;

  /* Recursive function to construct binary of size
    len from Inorder traversal in[] and Preorder traversal 
    pre[]. Initial values of inStrt and inEnd should be 
    0 and len -1. The function doesn't do any error 
    checking for cases where inorder and preorder 
    do not form a tree */
  public static Node buildTree(char[] in, char[] pre, int inStrt, int inEnd)
  {

    if(inStrt > inEnd)
    {
      return null;
    }

    /* Pick current node from Preorder traversal using preIndex 
        and increment preIndex */
    char curr = pre[preIndex++];
    Node tNode;
    tNode = new Node(curr);

    /* If this node has no children then return */
    if (inStrt == inEnd)
    {
      return tNode;
    }

    /* Else find the index of this node in Inorder traversal */
    int inIndex = mp.get(curr);

    /* Using index in Inorder traversal, construct left and 
        right subtress */
    tNode.left = buildTree(in, pre, inStrt, inIndex - 1);
    tNode.right = buildTree(in, pre, inIndex + 1, inEnd);
    return tNode;
  }

  // This function mainly creates an unordered_map, then
  // calls buildTree()
  public static Node buldTreeWrap(char[] in, char[] pre, int len)
  {
    for(int i = 0; i < len; i++)
    {
      mp.put(in[i], i);
    }
    return buildTree(in, pre, 0, len - 1);
  }

  /* This function is here just to test buildTree() */
  static void printInorder(Node node)
  {
    if(node == null)
    {
      return;
    }
    printInorder(node.left);
    System.out.print(node.data + " ");
    printInorder(node.right);
  }

  /* Driver code */ 
  public static void main (String[] args)
  {
    char[] in = {'D', 'B', 'E', 'A', 'F', 'C'};
    char[] pre = {'A', 'B', 'D', 'E', 'C', 'F'};
    int len = in.length;

    Tree.root=buldTreeWrap(in, pre, len);

    /* Let us test the built tree by printing 
        Inorder traversal */
    System.out.println("Inorder traversal of the constructed tree is");
    printInorder(root);
  }
}

// This code is contributed by avanitrachhadiya2155
Python
# Python3 program to construct tree using inorder
# and preorder 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
# len from Inorder traversal in[] and Preorder traversal
# pre[]. Initial values of inStrt and inEnd should be
# 0 and len -1. The function doesn't do any error
# checking for cases where inorder and preorder
# do not form a tree 
def buildTree(inn, pre, inStrt, inEnd):
    
    global preIndex, mp

    if (inStrt > inEnd):
        return None

    # Pick current node from Preorder traversal
    # using preIndex and increment preIndex 
    curr = pre[preIndex]
    preIndex += 1
    tNode = Node(curr)

    # If this node has no children then return 
    if (inStrt == inEnd):
        return tNode

    # Else find the index of this 
    # node in Inorder traversal 
    inIndex = mp[curr]

    # Using index in Inorder traversal, 
    # construct left and right subtress 
    tNode.left = buildTree(inn, pre, inStrt,
                           inIndex - 1)
    tNode.right = buildTree(inn, pre, inIndex + 1,
                            inEnd)

    return tNode

# This function mainly creates an 
# unordered_map, then calls buildTree()
def buldTreeWrap(inn, pre, lenn):
    
    global mp
    
    # Store indexes of all items so that we
    # we can quickly find later
    # unordered_map<char, int> mp;
    for i in range(lenn):
        mp[inn[i]] = i

    return buildTree(inn, pre, 0, lenn - 1)

# This function is here just to test buildTree() 
def printInorder(node):

    if (node == None):
        return
        
    printInorder(node.left)
    print(node.data, end = " ")
    printInorder(node.right)

# Driver code
if __name__ == '__main__':
    
    mp = {}
    preIndex = 0

    inn = [ 'D', 'B', 'E', 'A', 'F', 'C' ]
    pre = [ 'A', 'B', 'D', 'E', 'C', 'F' ]
    lenn = len(inn)

    root = buldTreeWrap(inn, pre,lenn)

    # Let us test the built tree by printing
    # Inorder traversal 
    print("Inorder traversal of "
          "the constructed tree is")
    
    printInorder(root)

# This code is contributed by mohit kumar 29
C#
/* C# program to construct tree using inorder
   and preorder traversals */
using System;
using System.Collections.Generic;

/* A binary tree node has data, pointer to left child 
and a pointer to right child */
public class Node 
{ 
    public char data; 
    public Node left, right; 
  
    public Node(char d) 
    { 
        data = d; 
        left = right = null; 
    } 
} 
public class Tree
{
    public static Node root;
  
    // Store indexes of all items so that we
    // we can quickly find later
    static Dictionary<char,int> mp = new Dictionary<char,int>();
    static int preIndex = 0;
  
    /* Recursive function to construct binary of size
    len from Inorder traversal in[] and Preorder traversal 
    pre[]. Initial values of inStrt and inEnd should be 
    0 and len -1. The function doesn't do any error 
    checking for cases where inorder and preorder 
    do not form a tree */
    static Node buildTree(char[] In, char[] pre,
                          int inStrt, int inEnd)
    {
        if(inStrt > inEnd)
        {
            return null;
        }
      
        /* Pick current node from Preorder traversal using preIndex 
        and increment preIndex */
        char curr = pre[preIndex++];
        Node tNode;
        tNode = new Node(curr);
      
        /* If this node has no children then return */
        if(inStrt == inEnd)
        {
            return tNode;
        }
      
        /* Else find the index of this node in Inorder traversal */
        int inIndex = mp[curr];
      
        /* Using index in Inorder traversal, construct left and 
        right subtress */
        tNode.left = buildTree(In, pre, inStrt, inIndex - 1);
        tNode.right = buildTree(In, pre, inIndex + 1, inEnd);
        return tNode;
    }
  
    // This function mainly creates an unordered_map, then
    // calls buildTree()
    public static Node buldTreeWrap(char[] In, char[] pre, int len)
    {
        for(int i = 0; i < len; i++)
        {
            mp.Add(In[i], i);
        }
        return buildTree(In, pre, 0, len - 1);
    }
  
    /* This function is here just to test buildTree() */
    static void printInorder(Node node)
    {
        if(node == null)
        {
            return;
        }
        printInorder(node.left);
        Console.Write(node.data + " ");
        printInorder(node.right);
    }
  
    /* Driver code */
    static public void Main (){
        char[] In = {'D', 'B', 'E', 'A', 'F', 'C'};
        char[] pre = {'A', 'B', 'D', 'E', 'C', 'F'};
        int len = In.Length;
        Tree.root = buldTreeWrap(In, pre, len);
      
        /* Let us test the built tree by printing 
        Inorder traversal */
        Console.WriteLine("Inorder traversal of the constructed tree is");
        printInorder(Tree.root);
    }
}

// This code is contributed by rag2127
JavaScript
<script>

/* Javascript program to construct tree using inorder
   and preorder traversals */
 
/* A binary tree node has data, pointer
   to left child and a pointer to right child */
class Node
{
    constructor(item)
    {
        this.data = item;
        this.left = this.right = null;
    }
}

let root;
let preIndex = 0;

/* Recursive function to construct binary of size
    len from Inorder traversal in[] and Preorder traversal
    pre[]. Initial values of inStrt and inEnd should be
    0 and len -1. The function doesn't do any error
    checking for cases where inorder and preorder
    do not form a tree */
function buildTree(In, pre, inStrt, inEnd, mp)
{
    if (inStrt > inEnd)
        return null;

    /* Pick current node from Preorder traversal using preIndex
        and increment preIndex */
    const tNode = new Node(pre[preIndex++]);

    // If this node has no children then return 
    if (inStrt === inEnd)
        return tNode;

    // Else find the index of this node in Inorder traversal 
    let inIndex = mp.get(tNode.data);

    /* Using index in Inorder traversal, construct left and
        right subtress */
    tNode.left = buildTree(In, pre, inStrt, inIndex - 1);
    tNode.right = buildTree(In, pre, inIndex + 1, inEnd);

    return tNode;
}

/* This function mainly creates an unordered_map, then
   calls buildTree() */
function buildTreeWrap(In, pre, start, end) {
    const mp = new Map();
    for (let i = 0; i < In.length; i++) {
        mp.set(In[i], i);
    }
    return buildTree(In, pre, start, end, mp);
}

// This function is here just to test buildTree() 
function printInorder(node)
{
    if (node == null)
            return;
 
    // First recur on left child 
    printInorder(node.left);

    // Then print the data of node
    document.write(node.data + " ");

    // Now recur on right child 
    printInorder(node.right);
}

// Driver code
let In = [ 'D', 'B', 'E', 'A', 'F', 'C' ];
let pre = [ 'A', 'B', 'D', 'E', 'C', 'F'];
let len = In.length;
root = buildTreeWrap(In, pre, 0, len - 1);

/* Let us test the built tree by printing
        Inorder traversal */
document.write("Inorder traversal of constructed tree is : <br>");
printInorder(root);

// This code is contributed by thakurballary

</script>

Output
Inorder traversal of the constructed tree is 
D B E A F C 

Time Complexity: O(n)
Auxiliary Space: O(n), The extra space is used to store the elements in the map also due to recursive function call stack.

Another Approach (Using Stack and Set)

Use the fact that InOrder traversal is Left-Root-Right and PreOrder traversal is Root-Left-Right. Also, the first node in the PreOrder traversal is always the root node and the first node in the InOrder traversal is the leftmost node in the tree.
Maintain two data structures: Stack (to store the path we visited while traversing PreOrder array) and Set (to maintain the node in which the next right subtree is expected).

1. Do below until you reach the leftmost node. 

Keep creating the nodes from the PreOrder traversal 

If the stack’s topmost element is not in the set, link the created node to the left child of the stack’s topmost element (if any), without popping the element. 
Else link the created node to the right child of the stack’s topmost element. Remove the stack’s topmost element from the set and the stack. 
Push the node to a stack.
 

1

2. Keep popping the nodes from the stack until either the stack is empty, or the topmost element of the stack compares to the current element of InOrder traversal. Once the loop is over, push the last node back into the stack and into the set.
 

2

3. Goto Step 1.
 

3

C++
// C++ program to construct a tree using
// inorder and preorder traversal
#include<bits/stdc++.h>
using namespace std; 

class TreeNode 
{
    public:
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) { val = x; }
};

set<TreeNode*> s;
stack<TreeNode*> st;

// Function to build tree using given traversal
TreeNode* buildTree(int preorder[], int inorder[],int n)
{

    TreeNode* root = NULL;
    for (int pre = 0, in = 0; pre < n;) 
    {

        TreeNode* node = NULL;
        do
        {
            node = new TreeNode(preorder[pre]);
            if (root == NULL)
            {
                root = node;
            }
            if (st.size() > 0) 
            {
                if (s.find(st.top()) != s.end())
                {
                    s.erase(st.top());
                    st.top()->right = node;
                    st.pop();
                }
                else
                {
                    st.top()->left = node;
                }
            }
            st.push(node);
        } while (preorder[pre++] != inorder[in] && pre < n);

        node = NULL;
        while (st.size() > 0 && in < n && 
                st.top()->val == inorder[in]) 
        {
            node = st.top();
            st.pop();
            in++;
        }

        if (node != NULL) 
        {
            s.insert(node);
            st.push(node);
        }
    }

    return root;
}

// Function to print tree in Inorder
void printInorder(TreeNode* node)
{
    if (node == NULL)
        return;

    /* first recur on left child */
    printInorder(node->left);

    /* then print the data of node */
    cout << node->val << " ";

    /* now recur on right child */
    printInorder(node->right);
}

// Driver code
int main()
{
    int in[] = { 9, 8, 4, 2, 10, 5, 10, 1, 6, 3, 13, 12, 7 };
    int pre[] = { 1, 2, 4, 8, 9, 5, 10, 10, 3, 6, 7, 12, 13 };
    int len = sizeof(in)/sizeof(int);

    TreeNode *root = buildTree(pre, in, len);

    printInorder(root);
    return 0;
}

// This code is contributed by Arnab Kundu
Java
// Java program to construct a tree using inorder and preorder traversal
import java.util.*;

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

class BinaryTree {
    static Set<TreeNode> set = new HashSet<>();
    static Stack<TreeNode> stack = new Stack<>();

    // Function to build tree using given traversal
    public TreeNode buildTree(int[] preorder, int[] inorder)
    {

        TreeNode root = null;
        for (int pre = 0, in = 0; pre < preorder.length;) {

            TreeNode node = null;
            do {
                node = new TreeNode(preorder[pre]);
                if (root == null) {
                    root = node;
                }
                if (!stack.isEmpty()) {
                    if (set.contains(stack.peek())) {
                        set.remove(stack.peek());
                        stack.pop().right = node;
                    }
                    else {
                        stack.peek().left = node;
                    }
                }
                stack.push(node);
            } while (preorder[pre++] != inorder[in] && pre < preorder.length);

            node = null;
            while (!stack.isEmpty() && in < inorder.length && 
                    stack.peek().val == inorder[in]) {
                node = stack.pop();
                in++;
            }

            if (node != null) {
                set.add(node);
                stack.push(node);
            }
        }

        return root;
    }

    // Function to print tree in Inorder
    void printInorder(TreeNode node)
    {
        if (node == null)
            return;

        /* first recur on left child */
        printInorder(node.left);

        /* then print the data of node */
        System.out.print(node.val + " ");

        /* now recur on right child */
        printInorder(node.right);
    }

    // driver program to test above functions
    public static void main(String args[])
    {
        BinaryTree tree = new BinaryTree();

        int in[] = new int[] { 9, 8, 4, 2, 10, 5, 10, 1, 6, 3, 13, 12, 7 };
        int pre[] = new int[] { 1, 2, 4, 8, 9, 5, 10, 10, 3, 6, 7, 12, 13 };
        int len = in.length;

        TreeNode root = tree.buildTree(pre, in);

        tree.printInorder(root);
    }
}
Python
# Python3 program to construct a tree using 
# inorder and preorder traversal 
class TreeNode:
    
    def __init__(self, x):      
        self.val = x
        self.left = None
        self.right = None

s = set()
st = []

# Function to build tree using given traversal 
def buildTree(preorder, inorder, n):
    root = None; 
    
    pre = 0
    in_t = 0
    
    while pre < n:
        node = None; 
        
        while True:    
            node = TreeNode(preorder[pre])
            
            if (root == None):            
                root = node; 
             
            if (len(st) > 0):        
                if (st[-1] in s):                
                    s.discard(st[-1]); 
                    st[-1].right = node; 
                    st.pop(); 
            
                else:                
                    st[-1].left = node; 
                        
            st.append(node); 
            
            if pre>=n or preorder[pre] == inorder[in_t]:
                pre += 1
                break
            pre += 1
            
        node = None; 
        
        while (len(st) > 0 and in_t < n and st[-1].val == inorder[in_t]):        
            node = st[-1]; 
            st.pop(); 
            in_t += 1
    

        if (node != None):        
            s.add(node); 
            st.append(node); 

    return root; 

# Function to print tree in_t Inorder 
def printInorder( node): 

    if (node == None):
        return; 

    ''' first recur on left child '''
    printInorder(node.left); 

    ''' then print data of node '''
    print(node.val, end=" "); 

    ''' now recur on right child '''
    printInorder(node.right); 

# Driver code 
if __name__=='__main__':
    
    in_t = [ 9, 8, 4, 2, 10, 5, 10, 1, 6, 3, 13, 12, 7 ]
    pre = [ 1, 2, 4, 8, 9, 5, 10, 10, 3, 6, 7, 12, 13 ]
    l = len(in_t) 

    root = buildTree(pre, in_t, l); 

    printInorder(root); 
    
    # This code is contributed by rutvik_56.
C#
// C# program to construct a tree 
// using inorder and preorder traversal
using System;
using System.Collections.Generic;

public class TreeNode 
{
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int x) { val = x; }
}

class GFG 
{
    static HashSet<TreeNode> set = new HashSet<TreeNode>();
    static Stack<TreeNode> stack = new Stack<TreeNode>();

    // Function to build tree using given traversal
    public TreeNode buildTree(int[] preorder, int[] inorder)
    {
        TreeNode root = null;
        for (int pre = 0, iN = 0; pre < preorder.Length;)
        {
            TreeNode node = null;
            do {
                node = new TreeNode(preorder[pre]);
                if (root == null)
                {
                    root = node;
                }
                if (stack.Count != 0) 
                {
                    if (set.Contains(stack.Peek())) 
                    {
                        set.Remove(stack.Peek());
                        stack.Pop().right = node;
                    }
                    else 
                    {
                        stack.Peek().left = node;
                    }
                }
                stack.Push(node);
            } while (preorder[pre++] != inorder[iN] && 
                     pre < preorder.Length);

            node = null;
            while (stack.Count != 0 && iN < inorder.Length && 
                   stack.Peek().val == inorder[iN]) 
            {
                node = stack.Pop();
                iN++;
            }
            if (node != null)
            {
                set.Add(node);
                stack.Push(node);
            }
        }
        return root;
    }

    // Function to print tree in Inorder
    void printInorder(TreeNode node)
    {
        if (node == null)
            return;

        /* first recur on left child */
        printInorder(node.left);

        /* then print the data of node */
        Console.Write(node.val + " ");

        /* now recur on right child */
        printInorder(node.right);
    }

    // Driver Code
    public static void Main(String []args)
    {
        GFG tree = new GFG();

        int []iN = new int[] { 9, 8, 4, 2, 10, 5, 10, 
                                 1, 6, 3, 13, 12, 7 };
        int []pre = new int[] { 1, 2, 4, 8, 9, 5, 10, 
                                 10, 3, 6, 7, 12, 13 };
        int len = iN.Length;

        TreeNode root = tree.buildTree(pre, iN);

        tree.printInorder(root);
    }
}

// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to construct a tree using inorder and preorder traversal
    
     
    class TreeNode
    {
        constructor(x) {
            this.val = x;
            this.left = null;
            this.right = null;
          }
    }
    
    let set = new Set();
    let stack = [];
    
    // Function to build tree using given traversal
    function buildTree(preorder,inorder)
    {
        let root = null;
        
        for (let pre = 0,In=0; pre < preorder.length;) {
 
            let node = null;
            do {
                node = new TreeNode(preorder[pre]);
                if (root == null) {
                    root = node;
                }
                if (stack.length!=0) {
                    if (set.has(stack[stack.length-1])) {
                        set.delete(stack[stack.length-1]);
                        stack.pop().right = node;
                    }
                    else {
                        stack[stack.length-1].left = node;
                    }
                }
                stack.push(node);
            } while (preorder[pre++] != inorder[In] && pre < preorder.length);
 
            node = null;
            while (stack.length!=0 && In < inorder.length &&
                    stack[stack.length-1].val == inorder[In]) {
                node = stack.pop();
                In++;
            }
 
            if (node != null) {
                set.add(node);
                stack.push(node);
            }
        }
 
        return root;
    }
    
    // Function to print tree in Inorder
    function printInorder(node)
    {
        if (node == null)
            return;
 
        /* first recur on left child */
        printInorder(node.left);
 
        /* then print the data of node */
        document.write(node.val + " ");
 
        /* now recur on right child */
        printInorder(node.right);
    }
    
    // driver program to test above functions
    let In=[9, 8, 4, 2, 10, 5, 10, 1, 6, 3, 13, 12, 7 ];
    let pre=[1, 2, 4, 8, 9, 5, 10, 10, 3, 6, 7, 12, 13 ];
    let len = In.length;
    let root=buildTree(pre, In);
    printInorder(root);
    
    
    // This code is contributed by unknown2108
</script>

Output
9 8 4 2 10 5 10 1 6 3 13 12 7 

Time Complexity: O(n), As we are traversing both the inorder and preorder just once.
Auxiliary Space: O(n), The extra space is used to store the elements in the stack and the set.

Note : This approach does not handle duplicates, To handle duplicates, we can use a hash map instead of hash set. Please refer this for sample implementation.

Construct a Binary Tree from Postorder and Inorder



Similar Reads

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
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
Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree.  Input:  Output: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 100 Input:  Output: Inorder Traversal: 8 12 20 22 25 30 40Preorder Tr
11 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
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 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
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
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
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
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
Construct a special tree from given preorder traversal
Given an array 'pre[]' that represents Preorder traversal of a special binary tree where every node has either 0 or 2 children. One more array 'preLN[]' is given which has only two possible values 'L' and 'N'. The value 'L' in 'preLN[]' indicates that the corresponding node in Binary Tree is a leaf node and value 'N' indicates that the correspondin
15+ min read
Construct a Binary Tree from Postorder and Inorder
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 Recommended PracticeTree from Postorder and InorderTry It! Approach: To s
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 Perfect Binary Tree from Preorder Traversal
Given an array pre[], representing the Preorder traversal of a Perfect Binary Tree consisting of N nodes, the task is to construct a Perfect Binary Tree from the given Preorder Traversal and return the root of the tree. Examples: Input: pre[] = {1, 2, 4, 5, 3, 6, 7}Output: 1 / \ / \ 2 3 / \ / \ / \ / \ 4 5 6 7 Input: pre[] = {1, 2, 3}Output: 1 / \
11 min read
Construct the full k-ary tree from its preorder traversal
Given an array that contains the preorder traversal of the full k-ary tree, construct the full k-ary tree and print its postorder traversal. A full k-ary tree is a tree where each node has either 0 or k children. Examples: Input : preorder[] = {1, 2, 5, 6, 7, 3, 8, 9, 10, 4} k = 3 Output : Postorder traversal of constructed full k-ary tree is: 5 6
10 min read
Construct BST from given preorder traversal using Stack
Given preorder traversal of a binary search tree, construct the BST.For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be root of following tree. 10 / \ 5 40 / \ \ 1 7 50 We have discussed O(n^2) and O(n) recursive solutions in the previous post. Following is a stack based iterative solution that works in O(n) time
13 min read
Construct BST from given preorder traversal using Sorting
Given preorder traversal of a binary search tree, construct the BST.For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be root of following tree. 10 / \ 5 40 / \ \ 1 7 50 We have discussed methods to construct binary search tree in previous posts.Here is another method to construct binary search tree when given pre
10 min read
Construct BST from given preorder traversal | Set 1
Given the preorder traversal of a binary search tree, construct the BST. Examples: Input: {10, 5, 1, 7, 40, 50}Output: 10 / \ 5 40 / \ \ 1 7 50 Recommended: Please try your approach on {IDE} first, before moving on to the solution.Naive approach: To solve the problem follow the below idea: The first element of preorder traversal is always the root.
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
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Data Structures | Tree Traversals | Question 1
Following function is supposed to calculate the maximum depth or height of a Binary tree -- the number of nodes along the longest path from the root node down to the farthest leaf node. int maxDepth(struct node* node) { if (node==NULL) return 0; else { /* compute the depth of each subtree */ int lDepth = maxDepth(node-&gt;left); int rDepth = maxDep
1 min read
Data Structures | Tree Traversals | Question 2
What is common in three different types of traversals (Inorder, Preorder and Postorder)? (A) Root is visited before right subtree (B) Left subtree is always visited before right subtree (C) Root is visited after left subtree (D) All of the above (E) None of the above Answer: (B) Explanation: The order of inorder traversal is LEFT ROOT RIGHT The ord
1 min read
Data Structures | Tree Traversals | Question 3
The inorder and preorder traversal of a binary tree are d b e a f c g and a b d e c f g, respectively. The postorder traversal of the binary tree is: (A) d e b f g c a (B) e d b g f c a (C) e d b f g c a (D) d e f g b c a Answer: (A) Explanation: Below is the given tree. a / \ / \ b c / \ / \ / \ / \ d e f g Quiz of this Question
1 min read
Data Structures | Tree Traversals | Question 4
What does the following function do for a given binary tree? int fun(struct node *root) { if (root == NULL) return 0; if (root-&gt;left == NULL &amp;&amp; root-&gt;right == NULL) return 0; return 1 + fun(root-&gt;left) + fun(root-&gt;right); } (A) Counts leaf nodes (B) Counts internal nodes (C) Returns height where height is defined as number of ed
2 min read
Data Structures | Tree Traversals | Question 5
Which of the following pairs of traversals is not sufficient to build a binary tree from the given traversals? (A) Preorder and Inorder (B) Preorder and Postorder (C) Inorder and Postorder (D) None of the Above Answer: (B) Explanation: See https://www.geeksforgeeks.org/if-you-are-given-two-traversal-sequences-can-you-construct-the-binary-tree/ for
1 min read
Data Structures | Tree Traversals | Question 6
Consider two binary operators '[Tex]\uparrow[/Tex] ' and '[Tex]\downarrow[/Tex]' with the precedence of operator [Tex]\downarrow[/Tex] being lower than that of the [Tex]\uparrow[/Tex] operator. Operator [Tex]\uparrow[/Tex] is right associative while operator [Tex]\downarrow[/Tex] is left associative. Which one of the following represents the parse
1 min read
Data Structures | Tree Traversals | Question 7
Which traversal of tree resembles the breadth first search of the graph? (A) Preorder (B) Inorder (C) Postorder (D) Level order Answer: (D) Explanation: Breadth first search visits all the neighbors first and then deepens into each neighbor one by one. The level order traversal of the tree also visits nodes on the current level and then goes to the
1 min read
Data Structures | Tree Traversals | Question 8
Which of the following tree traversal uses a queue data structure? (A) Preorder (B) Inorder (C) Postorder (D) Level order Answer: (D) Explanation: Level order traversal uses a queue data structure to visit the nodes level by level.Quiz of this Question
1 min read
Data Structures | Tree Traversals | Question 9
Which of the following cannot generate the full binary tree? (A) Inorder and Preorder (B) Inorder and Postorder (C) Preorder and Postorder (D) None of the above Answer: (D) Explanation: To generate a binary tree, two traversals are necessary and one of them must be inorder. But, a full binary tree can be generated from preorder and postorder traver
1 min read