Construct Special Binary Tree from given Inorder traversal
Last Updated :
23 Jul, 2025
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 tree
40
/ \
10 30
/ \
5 28
/ / \
1 15 20
The idea used in Construction of Tree from given Inorder and Preorder traversals can be used here. Let the given array is {1, 5, 10, 40, 30, 15, 28, 20}. The maximum element in the given array must be root. The elements on the left side of the maximum element are in the left subtree and the elements on the right side are in the right subtree.
40
/ \
{1,5,10} {30,15,28,20}
We recursively follow the above step for left and right subtrees, and finally, get the following tree.
40
/ \
10 30
/ \
5 28
/ / \
1 15 20
Algorithm: buildTree()
- Find index of the maximum element in array. The maximum element must be root of Binary Tree.
- Create a new tree node 'root' with the data as the maximum value found in step 1.
- Call buildTree for elements before the maximum element and make the built tree as left subtree of 'root'.
- Call buildTree for elements after the maximum element and make the built tree as right subtree of 'root'.
- return 'root'.
Below is the implementation of the above approach:
C++
/* C++ program to construct tree
from inorder traversal */
#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:
int data;
node* left;
node* right;
};
/* Prototypes of a utility function to get the maximum
value in inorder[start..end] */
int max(int inorder[], int strt, int end);
/* A utility function to allocate memory for a node */
node* newNode(int data);
/* Recursive function to construct binary of size len from
Inorder traversal inorder[]. Initial values of start and end
should be 0 and len -1. */
node* buildTree (int inorder[], int start, int end)
{
if (start > end)
return NULL;
/* Find index of the maximum element from Binary Tree */
int i = max (inorder, start, end);
/* Pick the maximum value and make it root */
node *root = newNode(inorder[i]);
/* If this is the only element in inorder[start..end],
then return it */
if (start == end)
return root;
/* Using index in Inorder traversal, construct left and
right subtress */
root->left = buildTree (inorder, start, i - 1);
root->right = buildTree (inorder, i + 1, end);
return root;
}
/* UTILITY FUNCTIONS */
/* Function to find index of the maximum value in arr[start...end] */
int max (int arr[], int strt, int end)
{
int i, max = arr[strt], maxind = strt;
for(i = strt + 1; i <= end; i++)
{
if(arr[i] > max)
{
max = arr[i];
maxind = i;
}
}
return maxind;
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode (int 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()
{
/* Assume that inorder traversal of following tree is given
40
/ \
10 30
/ \
5 28 */
int inorder[] = {5, 10, 40, 30, 28};
int len = sizeof(inorder)/sizeof(inorder[0]);
node *root = buildTree(inorder, 0, len - 1);
/* Let us test the built tree by printing Inorder traversal */
cout << "Inorder traversal of the constructed tree is \n";
printInorder(root);
return 0;
}
// This is code is contributed by rathbhupendra
C
/* program to construct tree from inorder traversal */
#include<stdio.h>
#include<stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Prototypes of a utility function to get the maximum
value in inorder[start..end] */
int max(int inorder[], int strt, int end);
/* A utility function to allocate memory for a node */
struct node* newNode(int data);
/* Recursive function to construct binary of size len from
Inorder traversal inorder[]. Initial values of start and end
should be 0 and len -1. */
struct node* buildTree (int inorder[], int start, int end)
{
if (start > end)
return NULL;
/* Find index of the maximum element from Binary Tree */
int i = max (inorder, start, end);
/* Pick the maximum value and make it root */
struct node *root = newNode(inorder[i]);
/* If this is the only element in inorder[start..end],
then return it */
if (start == end)
return root;
/* Using index in Inorder traversal, construct left and
right subtress */
root->left = buildTree (inorder, start, i-1);
root->right = buildTree (inorder, i+1, end);
return root;
}
/* UTILITY FUNCTIONS */
/* Function to find index of the maximum value in arr[start...end] */
int max (int arr[], int strt, int end)
{
int i, max = arr[strt], maxind = strt;
for(i = strt+1; i <= end; i++)
{
if(arr[i] > max)
{
max = arr[i];
maxind = i;
}
}
return maxind;
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode (int 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("%d ", node->data);
/* now recur on right child */
printInorder (node->right);
}
/* Driver program to test above functions */
int main()
{
/* Assume that inorder traversal of following tree is given
40
/ \
10 30
/ \
5 28 */
int inorder[] = {5, 10, 40, 30, 28};
int len = sizeof(inorder)/sizeof(inorder[0]);
struct node *root = buildTree(inorder, 0, len - 1);
/* Let us test the built tree by printing Inorder traversal */
printf("\n Inorder traversal of the constructed tree is \n");
printInorder(root);
return 0;
}
Java
// Java program to construct tree from inorder traversal
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
Node root;
/* Recursive function to construct binary of size len from
Inorder traversal inorder[]. Initial values of start and end
should be 0 and len -1. */
Node buildTree(int inorder[], int start, int end, Node node)
{
if (start > end)
return null;
/* Find index of the maximum element from Binary Tree */
int i = max(inorder, start, end);
/* Pick the maximum value and make it root */
node = new Node(inorder[i]);
/* If this is the only element in inorder[start..end],
then return it */
if (start == end)
return node;
/* Using index in Inorder traversal, construct left and
right subtress */
node.left = buildTree(inorder, start, i - 1, node.left);
node.right = buildTree(inorder, i + 1, end, node.right);
return node;
}
/* UTILITY FUNCTIONS */
/* Function to find index of the maximum value in arr[start...end] */
int max(int arr[], int strt, int end)
{
int i, max = arr[strt], maxind = strt;
for (i = strt + 1; i <= end; i++)
{
if (arr[i] > max)
{
max = arr[i];
maxind = i;
}
}
return maxind;
}
/* 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);
}
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
/* Assume that inorder traversal of following tree is given
40
/ \
10 30
/ \
5 28 */
int inorder[] = new int[]{5, 10, 40, 30, 28};
int len = inorder.length;
Node mynode = tree.buildTree(inorder, 0, len - 1, tree.root);
/* Let us test the built tree by printing Inorder traversal */
System.out.println("Inorder traversal of the constructed tree is ");
tree.printInorder(mynode);
}
}
// This code has been contributed by Mayank Jaiswal
Python3
# Python3 program to construct tree from
# inorder traversal
# Helper class that allocates a new node
# with the given data and None left and
# right pointers.
class newNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Prototypes of a utility function to get
# the maximum value in inorder[start..end]
# Recursive function to construct binary of
# size len from Inorder traversal inorder[].
# Initial values of start and end should be
# 0 and len -1.
def buildTree (inorder, start, end):
if start > end:
return None
# Find index of the maximum element
# from Binary Tree
i = Max (inorder, start, end)
# Pick the maximum value and make it root
root = newNode(inorder[i])
# If this is the only element in
# inorder[start..end], then return it
if start == end:
return root
# Using index in Inorder traversal,
# construct left and right subtress
root.left = buildTree (inorder, start, i - 1)
root.right = buildTree (inorder, i + 1, end)
return root
# UTILITY FUNCTIONS
# Function to find index of the maximum
# value in arr[start...end]
def Max(arr, strt, end):
i, Max = 0, arr[strt]
maxind = strt
for i in range(strt + 1, end + 1):
if arr[i] > Max:
Max = arr[i]
maxind = i
return maxind
# This function is here just to test buildTree()
def printInorder (node):
if node == 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 Code
if __name__ == '__main__':
# Assume that inorder traversal of
# following tree is given
# 40
# / \
# 10 30
# / \
#5 28
inorder = [5, 10, 40, 30, 28]
Len = len(inorder)
root = buildTree(inorder, 0, Len - 1)
# 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 PranchalK
C#
// C# program to construct tree
// from inorder traversal
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 item)
{
data = item;
left = right = null;
}
}
class GFG
{
public Node root;
/* Recursive function to construct binary
of size len from Inorder traversal inorder[].
Initial values of start and end should be 0
and len -1. */
public virtual Node buildTree(int[] inorder, int start,
int end, Node node)
{
if (start > end)
{
return null;
}
/* Find index of the maximum
element from Binary Tree */
int i = max(inorder, start, end);
/* Pick the maximum value and
make it root */
node = new Node(inorder[i]);
/* If this is the only element in
inorder[start..end], then return it */
if (start == end)
{
return node;
}
/* Using index in Inorder traversal,
construct left and right subtress */
node.left = buildTree(inorder, start,
i - 1, node.left);
node.right = buildTree(inorder, i + 1,
end, node.right);
return node;
}
/* UTILITY FUNCTIONS */
/* Function to find index of the
maximum value in arr[start...end] */
public virtual int max(int[] arr,
int strt, int end)
{
int i, max = arr[strt], maxind = strt;
for (i = strt + 1; i <= end; i++)
{
if (arr[i] > max)
{
max = arr[i];
maxind = i;
}
}
return maxind;
}
/* 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();
/* Assume that inorder traversal
of following tree is given
40
/ \
10 30
/ \
5 28 */
int[] inorder = new int[]{5, 10, 40, 30, 28};
int len = inorder.Length;
Node mynode = tree.buildTree(inorder, 0,
len - 1, tree.root);
/* Let us test the built tree by
printing Inorder traversal */
Console.WriteLine("Inorder traversal of " +
"the constructed tree is ");
tree.printInorder(mynode);
}
}
// This code is contributed by Shrikant13
JavaScript
<script>
// JavaScript program to construct tree
// from inorder 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 = null;
this.right = null;
}
}
var root = null;
/* Recursive function to construct binary
of size len from Inorder traversal inorder[].
Initial values of start and end should be 0
and len -1. */
function buildTree(inorder, start, end, node)
{
if (start > end)
{
return null;
}
/* Find index of the maximum
element from Binary Tree */
var i = max(inorder, start, end);
/* Pick the maximum value and
make it root */
node = new Node(inorder[i]);
/* If this is the only element in
inorder[start..end], then return it */
if (start == end)
{
return node;
}
/* Using index in Inorder traversal,
construct left and right subtress */
node.left = buildTree(inorder, start,
i - 1, node.left);
node.right = buildTree(inorder, i + 1,
end, node.right);
return node;
}
/* UTILITY FUNCTIONS */
/* Function to find index of the
maximum value in arr[start...end] */
function max(arr, strt, end)
{
var i, maxi = arr[strt], maxind = strt;
for (i = strt + 1; i <= end; i++)
{
if (arr[i] > maxi)
{
maxi = arr[i];
maxind = i;
}
}
return maxind;
}
/* 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
/* Assume that inorder traversal
of following tree is given
40
/ \
10 30
/ \
5 28 */
var inorder = [5, 10, 40, 30, 28];
var len = inorder.length;
var mynode = buildTree(inorder, 0, len - 1, root);
/* Let us test the built tree by
printing Inorder traversal */
document.write("Inorder traversal of " +
"the constructed tree is <br>");
printInorder(mynode);
</script>
OutputInorder traversal of the constructed tree is
5 10 40 30 28
Time Complexity: O(n^2)
Auxiliary Space: O(n), The extra space used is due to the recursion call stack.
Construct Special Binary Tree from given Inorder traversal
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem