Check if given Preorder, Inorder and Postorder traversals are of same binary tree
Last Updated : 7 Jul, 2026
Given the Preorder, Inorder, and Postordertraversal sequences of a binary tree. Determine whether these three traversal sequences can belong to the same binary tree.
Return true if all three traversals represent the same tree; otherwise, return false.
Examples:
Input: pre[] = [1, 2, 4, 5, 3], in[] = [4, 2, 5, 1, 3], post[] = [4, 5, 2, 3, 1] Output: true Explanation: All of the above three traversal sequences are of the same binary tree.
Input: pre[] = [1, 5, 4, 2, 3], in[] = [4, 2, 5, 1, 3], post[] = [4, 1, 2, 3, 5] Output: false Explanation: First element in preorder and the last element in postorder must be same, but here they are different (1 and 5). Hence, answer is false.
[Naive Approach] Tree Construction Using Inorder and Preorder - O(n ^ 2) Time and O(n) Space
The idea is to use the inorder and preorder (inorder and postorder can also be used) traversals(refer to this post) to build the tree. After constructing the tree, generate its postorder traversal and compare it with the given postorder traversal. If both traversals match, all three traversals belong to the same tree; otherwise, they do not.
Check whether the sizes of the preorder, inorder, and postorder traversals are equal. If not, return false.
Construct a binary tree using the given inorder and preorder traversals.
Pick the current node from preorder and locate its position in the inorder traversal.
Recursively construct the left and right subtrees using the inorder boundaries.
Generate the postorder traversal of the constructed tree and compare it with the given postorder traversal.
If the generated and given postorder traversals match completely, return true; otherwise, return false.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intval){data=val;left=right=nullptr;}};/* Search value in inorder vector */intsearch(vector<int>&in,intstart,intend,intvalue){for(inti=start;i<=end;i++){if(in[i]==value)returni;}return-1;}/* Build tree using inorder and preorder */Node*buildTree(vector<int>&in,vector<int>&pre,intinStart,intinEnd,int&preIndex){if(inStart>inEnd)returnnullptr;// Traversal exhaustedif(preIndex>=pre.size())returnnullptr;// Find current root in inorder// before creating nodeintinIndex=search(in,inStart,inEnd,pre[preIndex]);// Invalid traversalif(inIndex==-1)returnnullptr;// Create current nodeNode*root=newNode(pre[preIndex++]);// Leaf nodeif(inStart==inEnd)returnroot;// Construct left subtreeroot->left=buildTree(in,pre,inStart,inIndex-1,preIndex);// Construct right subtreeroot->right=buildTree(in,pre,inIndex+1,inEnd,preIndex);returnroot;}/* Compare generated postorder with given postorder */intcheckPostorder(Node*root,vector<int>&post,intindex){if(root==nullptr)returnindex;index=checkPostorder(root->left,post,index);if(index==-1)return-1;index=checkPostorder(root->right,post,index);if(index==-1)return-1;// Compare current nodeif(root->data==post[index])returnindex+1;return-1;}boolchecktree(vector<int>&pre,vector<int>&in,vector<int>&post){intn=in.size();// Traversals must have same sizeif(pre.size()!=n||post.size()!=n)returnfalse;intpreIndex=0;// Build tree from inorder// and preorderNode*root=buildTree(in,pre,0,n-1,preIndex);// Invalid tree constructionif(root==nullptr&&n>0)returnfalse;// Compare generated postorder// with given postorderintindex=checkPostorder(root,post,0);return(index==n);}intmain(){vector<int>in={4,2,5,1,3};vector<int>pre={1,2,4,5,3};vector<int>post={4,5,2,3,1};cout<<(checktree(pre,in,post)?"true":"false");return0;}
Java
importjava.util.*;classNode{publicintdata;publicNodeleft,right;Node(intval){data=val;left=right=null;}}publicclassGFG{/* Search value in inorder vector */staticintsearch(int[]in,intstart,intend,intvalue){for(inti=start;i<=end;i++){if(in[i]==value)returni;}return-1;}/* Build tree using inorder and preorder */staticNodebuildTree(int[]in,int[]pre,intinStart,intinEnd,int[]preIndex){if(inStart>inEnd)returnnull;// Traversal exhaustedif(preIndex[0]>=pre.length)returnnull;// Find current root in inorder// before creating nodeintinIndex=search(in,inStart,inEnd,pre[preIndex[0]]);// Invalid traversalif(inIndex==-1)returnnull;// Create current nodeNoderoot=newNode(pre[preIndex[0]++]);// Leaf nodeif(inStart==inEnd)returnroot;// Construct left subtreeroot.left=buildTree(in,pre,inStart,inIndex-1,preIndex);// Construct right subtreeroot.right=buildTree(in,pre,inIndex+1,inEnd,preIndex);returnroot;}/* Compare generated postorder with given postorder */staticintcheckPostorder(Noderoot,int[]post,intindex){if(root==null)returnindex;index=checkPostorder(root.left,post,index);if(index==-1)return-1;index=checkPostorder(root.right,post,index);if(index==-1)return-1;// Compare current nodeif(root.data==post[index])returnindex+1;return-1;}staticbooleanchecktree(int[]pre,int[]in,int[]post){intn=in.length;// Traversals must have same sizeif(pre.length!=n||post.length!=n)returnfalse;int[]preIndex={0};// Build tree from inorder// and preorderNoderoot=buildTree(in,pre,0,n-1,preIndex);// Invalid tree constructionif(root==null&&n>0)returnfalse;// Compare generated postorder// with given postorderintindex=checkPostorder(root,post,0);return(index==n);}publicstaticvoidmain(String[]args){int[]in={4,2,5,1,3};int[]pre={1,2,4,5,3};int[]post={4,5,2,3,1};System.out.println(checktree(pre,in,post)?"true":"false");}}
Python
classNode:def__init__(self,val):self.data=valself.left=Noneself.right=None""" Search value in inorder vector """defsearch(inorder,start,end,value):foriinrange(start,end+1):ifinorder[i]==value:returnireturn-1""" Build tree using inorder and preorder """defbuildTree(inorder,pre,inStart,inEnd,preIndex):ifinStart>inEnd:returnNone# Traversal exhaustedifpreIndex[0]>=len(pre):returnNone# Find current root in inorder# before creating nodeinIndex=search(inorder,inStart,inEnd,pre[preIndex[0]])# Invalid traversalifinIndex==-1:returnNone# Create current noderoot=Node(pre[preIndex[0]])preIndex[0]+=1# Leaf nodeifinStart==inEnd:returnroot# Construct left subtreeroot.left=buildTree(inorder,pre,inStart,inIndex-1,preIndex)# Construct right subtreeroot.right=buildTree(inorder,pre,inIndex+1,inEnd,preIndex)returnroot""" Compare generated postorder with given postorder """defcheckPostorder(root,post,index):ifrootisNone:returnindexindex=checkPostorder(root.left,post,index)ifindex==-1:return-1index=checkPostorder(root.right,post,index)ifindex==-1:return-1# Compare current nodeifroot.data==post[index]:returnindex+1return-1defchecktree(pre,inorder,post):n=len(inorder)# Traversals must have same sizeiflen(pre)!=norlen(post)!=n:returnFalsepreIndex=[0]# Build tree from inorder# and preorderroot=buildTree(inorder,pre,0,n-1,preIndex)# Invalid tree constructionifrootisNoneandn>0:returnFalse# Compare generated postorder# with given postorderindex=checkPostorder(root,post,0)returnindex==n# Driver Codeif__name__=="__main__":inorder=[4,2,5,1,3]pre=[1,2,4,5,3]post=[4,5,2,3,1]print(str(checktree(pre,inorder,post)).lower())
C#
usingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classGFG{/* Search value in inorder vector */staticintsearch(int[]inOrder,intstart,intend,intvalue){for(inti=start;i<=end;i++){if(inOrder[i]==value)returni;}return-1;}/* Build tree using inorder and preorder */staticNodebuildTree(int[]inOrder,int[]pre,intinStart,intinEnd,refintpreIndex){if(inStart>inEnd)returnnull;// Traversal exhaustedif(preIndex>=pre.Length)returnnull;// Find current root in inorder// before creating nodeintinIndex=search(inOrder,inStart,inEnd,pre[preIndex]);// Invalid traversalif(inIndex==-1)returnnull;// Create current nodeNoderoot=newNode(pre[preIndex++]);// Leaf nodeif(inStart==inEnd)returnroot;// Construct left subtreeroot.left=buildTree(inOrder,pre,inStart,inIndex-1,refpreIndex);// Construct right subtreeroot.right=buildTree(inOrder,pre,inIndex+1,inEnd,refpreIndex);returnroot;}/* Compare generated postorder with given postorder */staticintcheckPostorder(Noderoot,int[]post,intindex){if(root==null)returnindex;index=checkPostorder(root.left,post,index);if(index==-1)return-1;index=checkPostorder(root.right,post,index);if(index==-1)return-1;// Compare current nodeif(root.data==post[index])returnindex+1;return-1;}staticboolchecktree(int[]pre,int[]inOrder,int[]post){intn=inOrder.Length;// Traversals must have same sizeif(pre.Length!=n||post.Length!=n)returnfalse;intpreIndex=0;// Build tree from inorder// and preorderNoderoot=buildTree(inOrder,pre,0,n-1,refpreIndex);// Invalid tree constructionif(root==null&&n>0)returnfalse;// Compare generated postorder// with given postorderintindex=checkPostorder(root,post,0);return(index==n);}staticvoidMain(){int[]inOrder={4,2,5,1,3};int[]pre={1,2,4,5,3};int[]post={4,5,2,3,1};Console.WriteLine(checktree(pre,inOrder,post)?"true":"false");}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}/* Search value in inorder vector */functionsearch(inOrder,start,end,value){for(leti=start;i<=end;i++){if(inOrder[i]===value)returni;}return-1;}/* Build tree using inorder and preorder */functionbuildTree(inOrder,pre,inStart,inEnd,preIndex){if(inStart>inEnd)returnnull;// Traversal exhaustedif(preIndex.value>=pre.length)returnnull;// Find current root in inorder// before creating nodeletinIndex=search(inOrder,inStart,inEnd,pre[preIndex.value]);// Invalid traversalif(inIndex===-1)returnnull;// Create current nodeletroot=newNode(pre[preIndex.value++]);// Leaf nodeif(inStart===inEnd)returnroot;// Construct left subtreeroot.left=buildTree(inOrder,pre,inStart,inIndex-1,preIndex);// Construct right subtreeroot.right=buildTree(inOrder,pre,inIndex+1,inEnd,preIndex);returnroot;}/* Compare generated postorder with given postorder */functioncheckPostorder(root,post,index){if(root===null)returnindex;index=checkPostorder(root.left,post,index);if(index===-1)return-1;index=checkPostorder(root.right,post,index);if(index===-1)return-1;// Compare current nodeif(root.data===post[index])returnindex+1;return-1;}functionchecktree(pre,inOrder,post){letn=inOrder.length;// Traversals must have same sizeif(pre.length!==n||post.length!==n)returnfalse;letpreIndex={value:0};// Build tree from inorder// and preorderletroot=buildTree(inOrder,pre,0,n-1,preIndex);// Invalid tree constructionif(root===null&&n>0)returnfalse;// Compare generated postorder// with given postorderletindex=checkPostorder(root,post,0);returnindex===n;}// Driver CodeletinOrder=[4,2,5,1,3];letpre=[1,2,4,5,3];letpost=[4,5,2,3,1];console.log(checktree(pre,inOrder,post)?"true":"false");
Output
true
[Better Approach] Tree Construction With Hash Map - O(n) Time and O(n) Space
The idea is to construct the binary tree using the given inorder and preorder traversals (inorder and postorder can also be used) similar to the first approach. To avoid repeatedly searching for the root in the inorder traversal, store the indices of inorder elements in a hash map for constant-time lookup. This will reduce complexity from quadratic to linear.
Check whether the sizes of preorder, inorder, and postorder traversals are equal.
Store the index of each element of the inorder traversal in a hash map.
Construct the binary tree using preorder traversal and use the hash map to directly locate the root index in inorder.
Recursively build the left and right subtrees.
Generate and compare the postorder traversal of the constructed tree with the given postorder traversal.
Return true if both match; otherwise return false.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intval){data=val;left=right=nullptr;}};/* Build tree using inorder and preorder */Node*buildTree(vector<int>&in,vector<int>&pre,unordered_map<int,int>&mp,intinStart,intinEnd,int&preIndex){if(inStart>inEnd)returnnullptr;// Traversal exhaustedif(preIndex>=pre.size())returnnullptr;introotVal=pre[preIndex];// Root not presentif(mp.find(rootVal)==mp.end())returnnullptr;intinIndex=mp[rootVal];// Root index does not belong// to current subtreeif(inIndex<inStart||inIndex>inEnd)returnnullptr;// Create current nodeNode*root=newNode(pre[preIndex++]);// Leaf nodeif(inStart==inEnd)returnroot;// Construct left subtreeroot->left=buildTree(in,pre,mp,inStart,inIndex-1,preIndex);// Construct right subtreeroot->right=buildTree(in,pre,mp,inIndex+1,inEnd,preIndex);returnroot;}/* Compare generated postorder with given postorder */intcheckPostorder(Node*root,vector<int>&post,intindex){if(root==nullptr)returnindex;index=checkPostorder(root->left,post,index);if(index==-1)return-1;index=checkPostorder(root->right,post,index);if(index==-1)return-1;// Compare current nodeif(index<post.size()&&root->data==post[index])returnindex+1;return-1;}boolchecktree(vector<int>&pre,vector<int>&in,vector<int>&post){intn=in.size();// Traversals must have same sizeif(pre.size()!=n||post.size()!=n)returnfalse;/* Build hash map to store indices of inorder elements */unordered_map<int,int>mp;for(inti=0;i<n;i++){mp[in[i]]=i;}intpreIndex=0;// Build tree from inorder// and preorderNode*root=buildTree(in,pre,mp,0,n-1,preIndex);// Invalid tree constructionif(root==nullptr&&n>0)returnfalse;// Compare generated postorder// with given postorderintindex=checkPostorder(root,post,0);return(index==n);}intmain(){vector<int>in={4,2,5,1,3};vector<int>pre={1,2,4,5,3};vector<int>post={4,5,2,3,1};cout<<(checktree(pre,in,post)?"true":"false");return0;}
Java
importjava.util.*;classNode{publicintdata;publicNodeleft,right;Node(intval){data=val;left=right=null;}}publicclassGFG{/* Build tree using inorder and preorder */staticNodebuildTree(int[]in,int[]pre,HashMap<Integer,Integer>mp,intinStart,intinEnd,int[]preIndex){if(inStart>inEnd)returnnull;// Traversal exhaustedif(preIndex[0]>=pre.length)returnnull;introotVal=pre[preIndex[0]];// Root not presentif(!mp.containsKey(rootVal))returnnull;intinIndex=mp.get(rootVal);// Root index does not belong// to current subtreeif(inIndex<inStart||inIndex>inEnd)returnnull;// Create current nodeNoderoot=newNode(pre[preIndex[0]++]);// Leaf nodeif(inStart==inEnd)returnroot;// Construct left subtreeroot.left=buildTree(in,pre,mp,inStart,inIndex-1,preIndex);// Construct right subtreeroot.right=buildTree(in,pre,mp,inIndex+1,inEnd,preIndex);returnroot;}/* Compare generated postorder with given postorder */staticintcheckPostorder(Noderoot,int[]post,intindex){if(root==null)returnindex;index=checkPostorder(root.left,post,index);if(index==-1)return-1;index=checkPostorder(root.right,post,index);if(index==-1)return-1;// Compare current nodeif(index<post.length&&root.data==post[index])returnindex+1;return-1;}staticbooleanchecktree(int[]pre,int[]in,int[]post){intn=in.length;// Traversals must have same sizeif(pre.length!=n||post.length!=n)returnfalse;/* Build hash map to store indices of inorder elements */HashMap<Integer,Integer>mp=newHashMap<>();for(inti=0;i<n;i++){mp.put(in[i],i);}int[]preIndex={0};// Build tree from inorder// and preorderNoderoot=buildTree(in,pre,mp,0,n-1,preIndex);// Invalid tree constructionif(root==null&&n>0)returnfalse;// Compare generated postorder// with given postorderintindex=checkPostorder(root,post,0);return(index==n);}publicstaticvoidmain(String[]args){int[]in={4,2,5,1,3};int[]pre={1,2,4,5,3};int[]post={4,5,2,3,1};System.out.println(checktree(pre,in,post)?"true":"false");}}
Python
classNode:def__init__(self,val):self.data=valself.left=Noneself.right=None""" Build tree using inorder and preorder """defbuildTree(inorder,pre,mp,inStart,inEnd,preIndex):ifinStart>inEnd:returnNone# Traversal exhaustedifpreIndex[0]>=len(pre):returnNonerootVal=pre[preIndex[0]]# Root not presentifrootValnotinmp:returnNoneinIndex=mp[rootVal]# Root index does not belong# to current subtreeifinIndex<inStartorinIndex>inEnd:returnNone# Create current noderoot=Node(pre[preIndex[0]])preIndex[0]+=1# Leaf nodeifinStart==inEnd:returnroot# Construct left subtreeroot.left=buildTree(inorder,pre,mp,inStart,inIndex-1,preIndex)# Construct right subtreeroot.right=buildTree(inorder,pre,mp,inIndex+1,inEnd,preIndex)returnroot""" Compare generated postorder with given postorder """defcheckPostorder(root,post,index):ifrootisNone:returnindexindex=checkPostorder(root.left,post,index)ifindex==-1:return-1index=checkPostorder(root.right,post,index)ifindex==-1:return-1# Compare current nodeifindex<len(post)androot.data==post[index]:returnindex+1return-1defchecktree(pre,inorder,post):n=len(inorder)# Traversals must have same sizeiflen(pre)!=norlen(post)!=n:returnFalse""" Build hash map to store indices of inorder elements """mp={}foriinrange(n):mp[inorder[i]]=ipreIndex=[0]# Build tree from inorder# and preorderroot=buildTree(inorder,pre,mp,0,n-1,preIndex)# Invalid tree constructionifrootisNoneandn>0:returnFalse# Compare generated postorder# with given postorderindex=checkPostorder(root,post,0)returnindex==n# Driver Codeif__name__=="__main__":inorder=[4,2,5,1,3]pre=[1,2,4,5,3]post=[4,5,2,3,1]print(str(checktree(pre,inorder,post)).lower())
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classGFG{/* Build tree using inorder and preorder */staticNodebuildTree(int[]inOrder,int[]pre,Dictionary<int,int>mp,intinStart,intinEnd,refintpreIndex){if(inStart>inEnd)returnnull;// Traversal exhaustedif(preIndex>=pre.Length)returnnull;introotVal=pre[preIndex];// Root not presentif(!mp.ContainsKey(rootVal))returnnull;intinIndex=mp[rootVal];// Root index does not belong// to current subtreeif(inIndex<inStart||inIndex>inEnd)returnnull;// Create current nodeNoderoot=newNode(pre[preIndex++]);// Leaf nodeif(inStart==inEnd)returnroot;// Construct left subtreeroot.left=buildTree(inOrder,pre,mp,inStart,inIndex-1,refpreIndex);// Construct right subtreeroot.right=buildTree(inOrder,pre,mp,inIndex+1,inEnd,refpreIndex);returnroot;}/* Compare generated postorder with given postorder */staticintcheckPostorder(Noderoot,int[]post,intindex){if(root==null)returnindex;index=checkPostorder(root.left,post,index);if(index==-1)return-1;index=checkPostorder(root.right,post,index);if(index==-1)return-1;// Compare current nodeif(index<post.Length&&root.data==post[index])returnindex+1;return-1;}staticboolchecktree(int[]pre,int[]inOrder,int[]post){intn=inOrder.Length;// Traversals must have same sizeif(pre.Length!=n||post.Length!=n)returnfalse;/* Build hash map to store indices of inorder elements */Dictionary<int,int>mp=newDictionary<int,int>();for(inti=0;i<n;i++){mp[inOrder[i]]=i;}intpreIndex=0;// Build tree from inorder// and preorderNoderoot=buildTree(inOrder,pre,mp,0,n-1,refpreIndex);// Invalid tree constructionif(root==null&&n>0)returnfalse;// Compare generated postorder// with given postorderintindex=checkPostorder(root,post,0);return(index==n);}staticvoidMain(){int[]inOrder={4,2,5,1,3};int[]pre={1,2,4,5,3};int[]post={4,5,2,3,1};Console.WriteLine(checktree(pre,inOrder,post)?"true":"false");}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}/* Build tree using inorder and preorder */functionbuildTree(inOrder,pre,mp,inStart,inEnd,preIndex){if(inStart>inEnd)returnnull;// Traversal exhaustedif(preIndex.value>=pre.length)returnnull;letrootVal=pre[preIndex.value];// Root not presentif(!mp.has(rootVal))returnnull;letinIndex=mp.get(rootVal);// Root index does not belong// to current subtreeif(inIndex<inStart||inIndex>inEnd)returnnull;// Create current nodeletroot=newNode(pre[preIndex.value++]);// Leaf nodeif(inStart===inEnd)returnroot;// Construct left subtreeroot.left=buildTree(inOrder,pre,mp,inStart,inIndex-1,preIndex);// Construct right subtreeroot.right=buildTree(inOrder,pre,mp,inIndex+1,inEnd,preIndex);returnroot;}/* Compare generated postorder with given postorder */functioncheckPostorder(root,post,index){if(root===null)returnindex;index=checkPostorder(root.left,post,index);if(index===-1)return-1;index=checkPostorder(root.right,post,index);if(index===-1)return-1;// Compare current nodeif(index<post.length&&root.data===post[index])returnindex+1;return-1;}functionchecktree(pre,inOrder,post){letn=inOrder.length;// Traversals must have same sizeif(pre.length!==n||post.length!==n)returnfalse;/* Build hash map to store indices of inorder elements */letmp=newMap();for(leti=0;i<n;i++){mp.set(inOrder[i],i);}letpreIndex={value:0};// Build tree from inorder// and preorderletroot=buildTree(inOrder,pre,mp,0,n-1,preIndex);// Invalid tree constructionif(root===null&&n>0)returnfalse;// Compare generated postorder// with given postorderletindex=checkPostorder(root,post,0);returnindex===n;}// Driver CodeletinOrder=[4,2,5,1,3];letpre=[1,2,4,5,3];letpost=[4,5,2,3,1];console.log(checktree(pre,inOrder,post)?"true":"false");
Output
true
[Expected Approach] Without Constructing Tree - O(n) Time and O(n) Space
The idea is to avoid constructing the binary tree explicitly. Since the first element of preorder is the root, locate it in the inorder traversal to determine the left and right subtree boundaries. Using these boundaries, recursively verify the corresponding parts of preorder, inorder, and postorder traversals. If every subtree satisfies the conditions, then all three traversals belong to the same tree.
Check if the sizes of preorder, inorder, and postorder traversals are equal. If not, return false.
Store the indices of all elements from the inorder traversal in a hash map for constant-time lookup.
Take the first element of the current preorder range as the root of the subtree.
Find the root position in inorder using the hash map and determine the size of the left subtree.
Verify whether the root matches the last element of the current postorder range, then recursively validate the left and right subtrees.
If all recursive checks succeed, return true; otherwise return false.
C++
#include<bits/stdc++.h>usingnamespacestd;boolsolve(vector<int>&pre,vector<int>&in,vector<int>&post,unordered_map<int,int>&mp,intps,intpe,intis,intie,intpos,intpoe){// if the array lengths are 0,// then all of them are obviously equalif(ps>pe)returntrue;// if array lengths are 1,// then check if all of them are equalif(ps==pe){return(pre[ps]==in[is])&&(in[is]==post[pos]);}// Root of current subtreeintroot=pre[ps];// Check whether root exists// in inorder traversalif(mp.find(root)==mp.end())returnfalse;// Find root index in O(1)intidx=mp[root];// Root index should belong// to current subtreeif(idx<is||idx>ie)returnfalse;// Check whether root exists// at the current postorder root positionif(root!=post[poe])returnfalse;// Calculate left subtree sizeintleftSize=idx-is;// check for the left subtreeboolret1=solve(pre,in,post,mp,ps+1,ps+leftSize,is,idx-1,pos,pos+leftSize-1);// check for the right subtreeboolret2=solve(pre,in,post,mp,ps+leftSize+1,pe,idx+1,ie,pos+leftSize,poe-1);// return true only if both are correctreturn(ret1&&ret2);}boolchecktree(vector<int>&pre,vector<int>&in,vector<int>&post){intn=in.size();// Check if all the array lengths are equalif(pre.size()!=n||post.size()!=n)returnfalse;/* Build hash map to store indices of inorder elements */unordered_map<int,int>mp;for(inti=0;i<n;i++){mp[in[i]]=i;}returnsolve(pre,in,post,mp,0,n-1,0,n-1,0,n-1);}intmain(){// Traversal Arraysvector<int>in={4,2,5,1,3};vector<int>pre={1,2,4,5,3};vector<int>post={4,5,2,3,1};cout<<(checktree(pre,in,post)?"true":"false");return0;}
Java
importjava.util.*;classGFG{staticbooleansolve(int[]pre,int[]in,int[]post,HashMap<Integer,Integer>mp,intps,intpe,intis,intie,intpos,intpoe){// if the array lengths are 0,// then all of them are obviously equalif(ps>pe)returntrue;// if array lengths are 1,// then check if all of them are equalif(ps==pe){return(pre[ps]==in[is])&&(in[is]==post[pos]);}// Root of current subtreeintroot=pre[ps];// Check whether root exists// in inorder traversalif(!mp.containsKey(root))returnfalse;// Find root index in O(1)intidx=mp.get(root);// Root index should belong// to current subtreeif(idx<is||idx>ie)returnfalse;// Check whether root exists// at the current postorder root positionif(root!=post[poe])returnfalse;// Calculate left subtree sizeintleftSize=idx-is;// check for the left subtreebooleanret1=solve(pre,in,post,mp,ps+1,ps+leftSize,is,idx-1,pos,pos+leftSize-1);// check for the right subtreebooleanret2=solve(pre,in,post,mp,ps+leftSize+1,pe,idx+1,ie,pos+leftSize,poe-1);// return true only if both are correctreturn(ret1&&ret2);}staticbooleanchecktree(int[]pre,int[]in,int[]post){intn=in.length;// Check if all the array lengths are equalif(pre.length!=n||post.length!=n)returnfalse;/* Build hash map to store indices of inorder elements */HashMap<Integer,Integer>mp=newHashMap<>();for(inti=0;i<n;i++){mp.put(in[i],i);}returnsolve(pre,in,post,mp,0,n-1,0,n-1,0,n-1);}publicstaticvoidmain(String[]args){// Traversal Arraysint[]in={4,2,5,1,3};int[]pre={1,2,4,5,3};int[]post={4,5,2,3,1};System.out.println(checktree(pre,in,post)?"true":"false");}}
Python
defsolve(pre,inorder,post,mp,ps,pe,is_,ie,pos,poe):# if the array lengths are 0,# then all of them are obviously equalifps>pe:returnTrue# if array lengths are 1,# then check if all of them are equalifps==pe:return(pre[ps]==inorder[is_]andinorder[is_]==post[pos])# Root of current subtreeroot=pre[ps]# Check whether root exists# in inorder traversalifrootnotinmp:returnFalse# Find root index in O(1)idx=mp[root]# Root index should belong# to current subtreeifidx<is_oridx>ie:returnFalse# Check whether root exists# at the current postorder root positionifroot!=post[poe]:returnFalse# Calculate left subtree sizeleftSize=idx-is_# check for the left subtreeret1=solve(pre,inorder,post,mp,ps+1,ps+leftSize,is_,idx-1,pos,pos+leftSize-1)# check for the right subtreeret2=solve(pre,inorder,post,mp,ps+leftSize+1,pe,idx+1,ie,pos+leftSize,poe-1)# return true only if both are correctreturnret1andret2defchecktree(pre,inorder,post):n=len(inorder)# Check if all the array lengths are equaliflen(pre)!=norlen(post)!=n:returnFalse""" Build hash map to store indices of inorder elements """mp={}foriinrange(n):mp[inorder[i]]=ireturnsolve(pre,inorder,post,mp,0,n-1,0,n-1,0,n-1)# Driver Codeif__name__=="__main__":inorder=[4,2,5,1,3]pre=[1,2,4,5,3]post=[4,5,2,3,1]print("true"ifchecktree(pre,inorder,post)else"false")
C#
usingSystem;usingSystem.Collections.Generic;classGFG{staticboolsolve(int[]pre,int[]inorder,int[]post,Dictionary<int,int>mp,intps,intpe,intis_,intie,intpos,intpoe){// if the array lengths are 0,// then all of them are obviously equalif(ps>pe)returntrue;// if array lengths are 1,// then check if all of them are equalif(ps==pe){return(pre[ps]==inorder[is_])&&(inorder[is_]==post[pos]);}// Root of current subtreeintroot=pre[ps];// Check whether root exists// in inorder traversalif(!mp.ContainsKey(root))returnfalse;// Find root index in O(1)intidx=mp[root];// Root index should belong// to current subtreeif(idx<is_||idx>ie)returnfalse;// Check whether root exists// at the current postorder root positionif(root!=post[poe])returnfalse;// Calculate left subtree sizeintleftSize=idx-is_;// check for the left subtreeboolret1=solve(pre,inorder,post,mp,ps+1,ps+leftSize,is_,idx-1,pos,pos+leftSize-1);// check for the right subtreeboolret2=solve(pre,inorder,post,mp,ps+leftSize+1,pe,idx+1,ie,pos+leftSize,poe-1);// return true only if both are correctreturn(ret1&&ret2);}staticboolchecktree(int[]pre,int[]inorder,int[]post){intn=inorder.Length;// Check if all the array lengths are equalif(pre.Length!=n||post.Length!=n)returnfalse;/* Build hash map to store indices of inorder elements */Dictionary<int,int>mp=newDictionary<int,int>();for(inti=0;i<n;i++){mp[inorder[i]]=i;}returnsolve(pre,inorder,post,mp,0,n-1,0,n-1,0,n-1);}staticvoidMain(){// Traversal Arraysint[]inorder={4,2,5,1,3};int[]pre={1,2,4,5,3};int[]post={4,5,2,3,1};Console.WriteLine(checktree(pre,inorder,post)?"true":"false");}}
JavaScript
functionsolve(pre,inorder,post,mp,ps,pe,is_,ie,pos,poe){// if the array lengths are 0,// then all of them are obviously equalif(ps>pe)returntrue;// if array lengths are 1,// then check if all of them are equalif(ps===pe){return(pre[ps]===inorder[is_])&&(inorder[is_]===post[pos]);}// Root of current subtreeletroot=pre[ps];// Check whether root exists// in inorder traversalif(!mp.has(root))returnfalse;// Find root index in O(1)letidx=mp.get(root);// Root index should belong// to current subtreeif(idx<is_||idx>ie)returnfalse;// Check whether root exists// at the current postorder root positionif(root!==post[poe])returnfalse;// Calculate left subtree sizeletleftSize=idx-is_;// check for the left subtreeletret1=solve(pre,inorder,post,mp,ps+1,ps+leftSize,is_,idx-1,pos,pos+leftSize-1);// check for the right subtreeletret2=solve(pre,inorder,post,mp,ps+leftSize+1,pe,idx+1,ie,pos+leftSize,poe-1);// return true only if both are correctreturn(ret1&&ret2);}functionchecktree(pre,inorder,post){letn=inorder.length;// Check if all the array lengths are equalif(pre.length!==n||post.length!==n)returnfalse;/* Build hash map to store indices of inorder elements */letmp=newMap();for(leti=0;i<n;i++){mp.set(inorder[i],i);}returnsolve(pre,inorder,post,mp,0,n-1,0,n-1,0,n-1);}// Driver Codeletinorder=[4,2,5,1,3];letpre=[1,2,4,5,3];letpost=[4,5,2,3,1];console.log(checktree(pre,inorder,post)?"true":"false");