Construct Special Binary Tree from given Inorder traversal
View Discussion
Improve Article
Save Article
Like Article
- Difficulty Level : Medium
- Last Updated : 17 Jun, 2022
Given Inorder Traversal of a Special Binary Tree in which 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 20The 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 given array must be root. The elements on left side of the maximum element are in left subtree and elements on right side are in right subtree.
40
/ \
{1,5,10} {30,15,28,20}We recursively follow above step for left and right subtrees, and finally get the following tree.
40
/ \
10 30
/ \
5 28
/ / \
1 15 20Algorithm: 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’.
Implementation: Following is the implementation of the above algorithm.
C++
/* C++ program to construct treefrom inorder traversal */#include <bits/stdc++.h>usingnamespacestd;/* A binary tree node has data,pointer to left child anda pointer to right child */classnode{public:intdata;node* left;node* right;};/* Prototypes of a utility function to get the maximumvalue in inorder[start..end] */intmax(intinorder[],intstrt,intend);/* A utility function to allocate memory for a node */node* newNode(intdata);/* Recursive function to construct binary of size len fromInorder traversal inorder[]. Initial values of start and endshould be 0 and len -1. */node* buildTree (intinorder[],intstart,intend){if(start > end)returnNULL;/* Find index of the maximum element from Binary Tree */inti = 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)returnroot;/* Using index in Inorder traversal, construct left andright subtress */root->left = buildTree (inorder, start, i - 1);root->right = buildTree (inorder, i + 1, end);returnroot;}/* UTILITY FUNCTIONS *//* Function to find index of the maximum value in arr[start...end] */intmax (intarr[],intstrt,intend){inti, max = arr[strt], maxind = strt;for(i = strt + 1; i <= end; i++){if(arr[i] > max){max = arr[i];maxind = i;}}returnmaxind;}/* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode (intdata){node* Node =newnode();Node->data = data;Node->left = NULL;Node->right = NULL;returnNode;}/* This function is here just to test buildTree() */voidprintInorder (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*/intmain(){/* Assume that inorder traversal of following tree is given40/ \10 30/ \5 28 */intinorder[] = {5, 10, 40, 30, 28};intlen =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);return0;}// This is code is contributed by rathbhupendraC
/* program to construct tree from inorder traversal */#include<stdio.h>#include<stdlib.h>/* A binary tree node has data, pointer to left childand a pointer to right child */structnode{intdata;structnode* left;structnode* right;};/* Prototypes of a utility function to get the maximumvalue in inorder[start..end] */intmax(intinorder[],intstrt,intend);/* A utility function to allocate memory for a node */structnode* newNode(intdata);/* Recursive function to construct binary of size len fromInorder traversal inorder[]. Initial values of start and endshould be 0 and len -1. */structnode* buildTree (intinorder[],intstart,intend){if(start > end)returnNULL;/* Find index of the maximum element from Binary Tree */inti = max (inorder, start, end);/* Pick the maximum value and make it root */structnode *root = newNode(inorder[i]);/* If this is the only element in inorder[start..end],then return it */if(start == end)returnroot;/* Using index in Inorder traversal, construct left andright subtress */root->left = buildTree (inorder, start, i-1);root->right = buildTree (inorder, i+1, end);returnroot;}/* UTILITY FUNCTIONS *//* Function to find index of the maximum value in arr[start...end] */intmax (intarr[],intstrt,intend){inti, max = arr[strt], maxind = strt;for(i = strt+1; i <= end; i++){if(arr[i] > max){max = arr[i];maxind = i;}}returnmaxind;}/* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */structnode* newNode (intdata){structnode* node = (structnode*)malloc(sizeof(structnode));node->data = data;node->left = NULL;node->right = NULL;returnnode;}/* This function is here just to test buildTree() */voidprintInorder (structnode* 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 */intmain(){/* Assume that inorder traversal of following tree is given40/ \10 30/ \5 28 */intinorder[] = {5, 10, 40, 30, 28};intlen =sizeof(inorder)/sizeof(inorder[0]);structnode *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);return0;}Java
// Java program to construct tree from inorder traversal/* A binary tree node has data, pointer to left childand a pointer to right child */classNode{intdata;Node left, right;Node(intitem){data = item;left = right =null;}}classBinaryTree{Node root;/* Recursive function to construct binary of size len fromInorder traversal inorder[]. Initial values of start and endshould be 0 and len -1. */Node buildTree(intinorder[],intstart,intend, Node node){if(start > end)returnnull;/* Find index of the maximum element from Binary Tree */inti = max(inorder, start, end);/* Pick the maximum value and make it root */node =newNode(inorder[i]);/* If this is the only element in inorder[start..end],then return it */if(start == end)returnnode;/* Using index in Inorder traversal, construct left andright subtress */node.left = buildTree(inorder, start, i -1, node.left);node.right = buildTree(inorder, i +1, end, node.right);returnnode;}/* UTILITY FUNCTIONS *//* Function to find index of the maximum value in arr[start...end] */intmax(intarr[],intstrt,intend){inti, max = arr[strt], maxind = strt;for(i = strt +1; i <= end; i++){if(arr[i] > max){max = arr[i];maxind = i;}}returnmaxind;}/* This function is here just to test buildTree() */voidprintInorder(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);}publicstaticvoidmain(String args[]){BinaryTree tree =newBinaryTree();/* Assume that inorder traversal of following tree is given40/ \10 30/ \5 28 */intinorder[] =newint[]{5,10,40,30,28};intlen = 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 JaiswalPython3
# 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.classnewNode:def__init__(self, data):self.data=dataself.left=Noneself.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.defbuildTree (inorder, start, end):ifstart > end:returnNone# Find index of the maximum element# from Binary Treei=Max(inorder, start, end)# Pick the maximum value and make it rootroot=newNode(inorder[i])# If this is the only element in# inorder[start..end], then return itifstart==end:returnroot# Using index in Inorder traversal,# construct left and right subtressroot.left=buildTree (inorder, start, i-1)root.right=buildTree (inorder, i+1, end)returnroot# UTILITY FUNCTIONS# Function to find index of the maximum# value in arr[start...end]defMax(arr, strt, end):i,Max=0, arr[strt]maxind=strtforiinrange(strt+1, end+1):ifarr[i] >Max:Max=arr[i]maxind=ireturnmaxind# This function is here just to test buildTree()defprintInorder (node):ifnode==None:return# first recur on left childprintInorder (node.left)# then print the data of node(node.data, end=" ")# now recur on right childprintInorder (node.right)# Driver Codeif__name__=='__main__':# Assume that inorder traversal of# following tree is given# 40# / \# 10 30# / \#5 28inorder=[5,10,40,30,28]Len=len(inorder)root=buildTree(inorder,0,Len-1)# Let us test the built tree by# printing Inorder traversal("Inorder traversal of the","constructed tree is ")printInorder(root)# This code is contributed by PranchalKC#
// C# program to construct tree// from inorder traversalusingSystem;/* A binary tree node has data,pointer to left child and a pointerto right child */publicclassNode{publicintdata;publicNode left, right;publicNode(intitem){data = item;left = right =null;}}classGFG{publicNode root;/* Recursive function to construct binaryof size len from Inorder traversal inorder[].Initial values of start and end should be 0and len -1. */publicvirtualNode buildTree(int[] inorder,intstart,intend, Node node){if(start > end){returnnull;}/* Find index of the maximumelement from Binary Tree */inti = max(inorder, start, end);/* Pick the maximum value andmake it root */node =newNode(inorder[i]);/* If this is the only element ininorder[start..end], then return it */if(start == end){returnnode;}/* 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);returnnode;}/* UTILITY FUNCTIONS *//* Function to find index of themaximum value in arr[start...end] */publicvirtualintmax(int[] arr,intstrt,intend){inti, max = arr[strt], maxind = strt;for(i = strt + 1; i <= end; i++){if(arr[i] > max){max = arr[i];maxind = i;}}returnmaxind;}/* This function is here justto test buildTree() */publicvirtualvoidprintInorder(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 CodepublicstaticvoidMain(string[] args){GFG tree =newGFG();/* Assume that inorder traversalof following tree is given40/ \10 30/ \5 28 */int[] inorder =newint[]{5, 10, 40, 30, 28};intlen = inorder.Length;Node mynode = tree.buildTree(inorder, 0,len - 1, tree.root);/* Let us test the built tree byprinting Inorder traversal */Console.WriteLine("Inorder traversal of "+"the constructed tree is ");tree.printInorder(mynode);}}// This code is contributed by Shrikant13Javascript
<script>// JavaScript program to construct tree// from inorder traversal/* A binary tree node has data,pointer to left child and a pointerto right child */class Node{constructor(item){this.data = item;this.left =null;this.right =null;}}varroot =null;/* Recursive function to construct binaryof size len from Inorder traversal inorder[].Initial values of start and end should be 0and len -1. */functionbuildTree(inorder, start, end, node){if(start > end){returnnull;}/* Find index of the maximumelement from Binary Tree */vari = max(inorder, start, end);/* Pick the maximum value andmake it root */node =newNode(inorder[i]);/* If this is the only element ininorder[start..end], then return it */if(start == end){returnnode;}/* 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);returnnode;}/* UTILITY FUNCTIONS *//* Function to find index of themaximum value in arr[start...end] */functionmax(arr, strt, end){vari, maxi = arr[strt], maxind = strt;for(i = strt + 1; i <= end; i++){if(arr[i] > maxi){maxi = arr[i];maxind = i;}}returnmaxind;}/* This function is here justto test buildTree() */functionprintInorder(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 traversalof following tree is given40/ \10 30/ \5 28 */varinorder = [5, 10, 40, 30, 28];varlen = inorder.length;varmynode = buildTree(inorder, 0, len - 1, root);/* Let us test the built tree byprinting 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 28Time Complexity: O(n^2)
My Personal Notes arrow_drop_upRecommended ArticlesPage :Article Contributed By :Improved By :Article Tags :Practice Tags :



.png)