Full Binary Tree using its Preorder and Mirror's Preorder
Last Updated : 27 May, 2026
Given two arrays pre[] and preMirror[] of size n containing unique elements, where pre[] represents the preorder traversal of a full binary tree and preMirror[] represents the preorder traversal of its mirror tree, construct the original full binary tree using these traversals.
Note: A general binary tree cannot be uniquely constructed using these two traversals. However, a full binary tree can be constructed uniquely from the given traversals without any ambiguity.
Examples:
Input: pre[] = {0,1,2}, preMirror[] = {0,2,1} Output: {0, 1, 2} Explanation: The tree will look like
Input: pre[] = {1, 2, 4, 5, 3, 6, 7}, preMirror[] = {1, 3, 7, 6, 2, 5, 4} Output: {1, 2, 4, 5, 3, 6, 7} Explanation: The tree will look like
[Naive Approach] Linear Search in Mirror Preorder – O(n²) Time and O(n) Space
We use pre[] to pick nodes in root order, and preMirror[] to determine how the tree is split into left and right subtrees.
Take the first element of pre[] as the root.
Maintain a variable preIndex to track the current position in pre[].
For the next element in pre[], find its position in preMirror[]. This position divides the current range into left subtree range and right subtree range. In the above example pre[] = {1, 2, 4, 5, 3, 6, 7}, preMirror[] = {1, 3, 7, 6, 2, 5, 4}. Using the position of 2 in preMirror[], we can find left and right subtrees.
Recursively construct the left subtree using the right part of the split range and the right subtree using the left part of the split range.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Recursive function to construct full binary treeNode*constructBinaryTreeUtil(vector<int>&pre,vector<int>&preMirror,int&preIndex,intl,inth,intn){// Base caseif(preIndex>=n||l>h)returnnullptr;// Create root nodeNode*root=newNode(pre[preIndex++]);// If single elementif(l==h)returnroot;// Find next preorder element in preMirrorinti;for(i=l;i<=h;i++){if(pre[preIndex]==preMirror[i])break;}// Build left and right subtreesif(i<=h){root->left=constructBinaryTreeUtil(pre,preMirror,preIndex,i,h,n);root->right=constructBinaryTreeUtil(pre,preMirror,preIndex,l+1,i-1,n);}returnroot;}Node*constructBinaryTree(vector<int>&pre,vector<int>&preMirror){intn=pre.size();intpreIndex=0;returnconstructBinaryTreeUtil(pre,preMirror,preIndex,0,n-1,n);}// Inorder traversalvoidprintInorder(Node*root){if(root==nullptr)return;printInorder(root->left);cout<<root->data<<" ";printInorder(root->right);}intmain(){vector<int>pre={1,2,4,5,3,6,7};vector<int>preMirror={1,3,7,6,2,5,4};Node*root=constructBinaryTree(pre,preMirror);printInorder(root);return0;}
Java
importjava.util.HashMap;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGFG{// Recursive function to construct full binary treepublicstaticNodeconstructBinaryTreeUtil(int[]pre,int[]preMirror,int[]preIndex,intl,inth,intn){// Base caseif(preIndex[0]>=n||l>h)returnnull;// Create root nodeNoderoot=newNode(pre[preIndex[0]++]);// If single elementif(l==h)returnroot;// Find next preorder element in preMirrorinti;for(i=l;i<=h;i++){if(pre[preIndex[0]]==preMirror[i])break;}// Build subtreesif(i<=h){root.left=constructBinaryTreeUtil(pre,preMirror,preIndex,i,h,n);root.right=constructBinaryTreeUtil(pre,preMirror,preIndex,l+1,i-1,n);}returnroot;}publicstaticNodeconstructBinaryTree(int[]pre,int[]preMirror){intn=pre.length;int[]preIndex={0};returnconstructBinaryTreeUtil(pre,preMirror,preIndex,0,n-1,n);}// Inorder traversalpublicstaticvoidprintInorder(Noderoot){if(root==null)return;printInorder(root.left);System.out.print(root.data+" ");printInorder(root.right);}publicstaticvoidmain(String[]args){int[]pre={1,2,4,5,3,6,7};int[]preMirror={1,3,7,6,2,5,4};Noderoot=constructBinaryTree(pre,preMirror);printInorder(root);}}
Python
classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Recursive function to construct full binary treedefconstructBinaryTreeUtil(pre,preMirror,preIndex,l,h,n):# Base caseifpreIndex[0]>=norl>h:returnNone# Create root noderoot=Node(pre[preIndex[0]])preIndex[0]+=1# If single elementifl==h:returnroot# Find next preorder element in preMirrori=lwhilei<=h:ifpre[preIndex[0]]==preMirror[i]:breaki+=1# Build subtreesifi<=h:root.left=constructBinaryTreeUtil(pre,preMirror,preIndex,i,h,n)root.right=constructBinaryTreeUtil(pre,preMirror,preIndex,l+1,i-1,n)returnroot# Wrapper functiondefconstructBinaryTree(pre,preMirror):n=len(pre)preIndex=[0]returnconstructBinaryTreeUtil(pre,preMirror,preIndex,0,n-1,n)# Inorder traversaldefinorder(root):ifnotroot:returninorder(root.left)print(root.data,end=" ")inorder(root.right)if__name__=="__main__":pre=[1,2,4,5,3,6,7]preMirror=[1,3,7,6,2,5,4]root=constructBinaryTree(pre,preMirror)inorder(root)
C#
usingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}// Recursive function to construct full binary treeclassGFG{staticNodeconstructBinaryTreeUtil(int[]pre,int[]preMirror,int[]preIndex,intl,inth,intn){// Base caseif(preIndex[0]>=n||l>h)returnnull;// Create root nodeNoderoot=newNode(pre[preIndex[0]]);preIndex[0]++;// If single elementif(l==h)returnroot;// Find next preorder element in preMirrorinti=l;for(;i<=h;i++){if(pre[preIndex[0]]==preMirror[i])break;}// Build subtreesif(i<=h){root.left=constructBinaryTreeUtil(pre,preMirror,preIndex,i,h,n);root.right=constructBinaryTreeUtil(pre,preMirror,preIndex,l+1,i-1,n);}returnroot;}staticNodeconstructBinaryTree(int[]pre,int[]preMirror){intn=pre.Length;int[]preIndex=newint[]{0};returnconstructBinaryTreeUtil(pre,preMirror,preIndex,0,n-1,n);}staticvoidinorder(Noderoot){if(root==null)return;inorder(root.left);Console.Write(root.data+" ");inorder(root.right);}staticvoidMain(){int[]pre={1,2,4,5,3,6,7};int[]preMirror={1,3,7,6,2,5,4};Noderoot=constructBinaryTree(pre,preMirror);inorder(root);}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Recursive function to construct full binary treefunctionconstructBinaryTreeUtil(pre,preMirror,preIndex,l,h,n){// Base caseif(preIndex[0]>=n||l>h)returnnull;// Create root nodeletroot=newNode(pre[preIndex[0]]);preIndex[0]++;// If single elementif(l===h)returnroot;// Find next preorder element in preMirrorleti=l;while(i<=h){if(pre[preIndex[0]]===preMirror[i])break;i++;}// Build subtreesif(i<=h){root.left=constructBinaryTreeUtil(pre,preMirror,preIndex,i,h,n);root.right=constructBinaryTreeUtil(pre,preMirror,preIndex,l+1,i-1,n);}returnroot;}// WrapperfunctionconstructBinaryTree(pre,preMirror){letn=pre.length;letpreIndex=[0];returnconstructBinaryTreeUtil(pre,preMirror,preIndex,0,n-1,n);}// Inorder traversalfunctioninorder(root){if(!root)return;inorder(root.left);process.stdout.write(root.data+" ");inorder(root.right);}// Drive codeletpre=[1,2,4,5,3,6,7];letpreMirror=[1,3,7,6,2,5,4];letroot=constructBinaryTree(pre,preMirror);inorder(root);
Output
4 2 5 1 6 3 7
[Expected Approach] Hash Map or Dictionary Optimization – O(n) Time and O(n) Space
To optimize the above solution, we store the index of every element of preMirror[] in a Hash Map so that we can find the split position in O(1) time. This helps us quickly divide the current range into left and right subtrees and build the tree efficiently using recursion.
Store all elements of preMirror[] in a Hash Map with their indices for fast lookup.
Take the first element of pre[] as the root and maintain a pointer preIndex.
For the next element in pre[], use the Hash Map to directly find its index in preMirror[].
This index divides the current range into left subtree range and right subtree range.
Recursively construct the left subtree and right subtree using the same logic.
Store indices of preMirror[] in HashMap: {1→0, 3→1, 7→2, 6→3, 2→4, 5→5, 4→6}
Step 2:
Next element in pre[] is 2
Using HashMap, index of 2 in preMirror[] = 4
This splits range into:
Left subtree range: [4 ... 6]
Right subtree range: [1 ... 3]
Step 3: Recursively build left and right subtrees using the same process.
The tree is successfully constructed, and its inorder traversal becomes: 4 2 5 1 6 3 7
C++
#include<bits/stdc++.h>usingnamespacestd;// Definition of NodeclassNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=NULL;}};// Recursive function to construct binary treeNode*buildTree(vector<int>&pre,vector<int>&preMirror,int&preIndex,intleft,intright,unordered_map<int,int>&mp,intn){// Base caseif(preIndex>=n||left>right)returnNULL;// Create current nodeNode*root=newNode(pre[preIndex++]);// If leaf nodeif(left==right)returnroot;// Find next preorder element index in preMirrorintmirrorIndex=mp[pre[preIndex]];// Construct left and right subtreeif(mirrorIndex>=left&&mirrorIndex<=right){// Construct left subtreeroot->left=buildTree(pre,preMirror,preIndex,mirrorIndex,right,mp,n);// Construct right subtreeroot->right=buildTree(pre,preMirror,preIndex,left+1,mirrorIndex-1,mp,n);}returnroot;}// Wrapper function to construct binary treeNode*constructBinaryTree(vector<int>&pre,vector<int>&preMirror){intn=pre.size();// Store indices of mirror preorder traversalunordered_map<int,int>mp;for(inti=0;i<n;i++){mp[preMirror[i]]=i;}intpreIndex=0;returnbuildTree(pre,preMirror,preIndex,0,n-1,mp,n);}// Inorder traversalvoidinorder(Node*root){if(!root)return;inorder(root->left);cout<<root->data<<" ";inorder(root->right);}intmain(){vector<int>pre={1,2,4,5,3,6,7};vector<int>preMirror={1,3,7,6,2,5,4};Node*root=constructBinaryTree(pre,preMirror);inorder(root);return0;}
Java
// Definition of NodeclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}publicclassGFG{// Recursive function to construct binary treestaticNodebuildTree(int[]pre,int[]preMirror,int[]preIndex,intleft,intright,HashMap<Integer,Integer>mp,intn){// Base caseif(preIndex[0]>=n||left>right)returnnull;// Create current nodeNoderoot=newNode(pre[preIndex[0]++]);// If leaf nodeif(left==right)returnroot;// Find next preorder element index in preMirrorintmirrorIndex=mp.get(pre[preIndex[0]]);// Construct left and right subtreeif(mirrorIndex>=left&&mirrorIndex<=right){// Construct left subtreeroot.left=buildTree(pre,preMirror,preIndex,mirrorIndex,right,mp,n);// Construct right subtreeroot.right=buildTree(pre,preMirror,preIndex,left+1,mirrorIndex-1,mp,n);}returnroot;}// Wrapper function to construct binary treestaticNodeconstructBinaryTree(int[]pre,int[]preMirror){intn=pre.length;// Store indices of mirror preorder traversalHashMap<Integer,Integer>mp=newHashMap<>();for(inti=0;i<n;i++){mp.put(preMirror[i],i);}int[]preIndex=newint[]{0};returnbuildTree(pre,preMirror,preIndex,0,n-1,mp,n);}// Inorder traversalstaticvoidinorder(Noderoot){if(root==null)return;inorder(root.left);System.out.print(root.data+" ");inorder(root.right);}// main functionpublicstaticvoidmain(String[]args){int[]pre={1,2,4,5,3,6,7};int[]preMirror={1,3,7,6,2,5,4};Noderoot=constructBinaryTree(pre,preMirror);inorder(root);}}
Python
# Definition of NodeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Recursive function to construct binary treedefbuildTree(pre,preMirror,preIndex,left,right,mp,n):# Base caseifpreIndex[0]>=norleft>right:returnNone# Create current noderoot=Node(pre[preIndex[0]])preIndex[0]+=1# If leaf nodeifleft==right:returnroot# Find next preorder element index in preMirrormirrorIndex=mp[pre[preIndex[0]]]# Construct left and right subtreeifmirrorIndex>=leftandmirrorIndex<=right:# Construct left subtreeroot.left=buildTree(pre,preMirror,preIndex,mirrorIndex,right,mp,n)# Construct right subtreeroot.right=buildTree(pre,preMirror,preIndex,left+1,mirrorIndex-1,mp,n)returnroot# Wrapper function to construct binary treedefconstructBinaryTree(pre,preMirror):n=len(pre)# Store indices of mirror preorder traversalmp={}foriinrange(n):mp[preMirror[i]]=ipreIndex=[0]returnbuildTree(pre,preMirror,preIndex,0,n-1,mp,n)# Inorder traversaldefinorder(root):ifnotroot:returninorder(root.left)print(root.data,end=" ")inorder(root.right)if__name__=="__main__":pre=[1,2,4,5,3,6,7]preMirror=[1,3,7,6,2,5,4]root=constructBinaryTree(pre,preMirror)inorder(root)
C#
usingSystem;usingSystem.Collections.Generic;// Definition of NodeclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGFG{// Recursive function to construct binary treestaticNodebuildTree(int[]pre,int[]preMirror,int[]preIndex,intleft,intright,Dictionary<int,int>mp,intn){// Base caseif(preIndex[0]>=n||left>right)returnnull;// Create current nodeNoderoot=newNode(pre[preIndex[0]++]);// If leaf nodeif(left==right)returnroot;// Find next preorder element index in preMirrorintmirrorIndex=mp[pre[preIndex[0]]];// Construct left and right subtreeif(mirrorIndex>=left&&mirrorIndex<=right){// Construct left subtreeroot.left=buildTree(pre,preMirror,preIndex,mirrorIndex,right,mp,n);// Construct right subtreeroot.right=buildTree(pre,preMirror,preIndex,left+1,mirrorIndex-1,mp,n);}returnroot;}// Wrapper function to construct binary treestaticNodeconstructBinaryTree(int[]pre,int[]preMirror){intn=pre.Length;// Store indices of mirror preorder traversalDictionary<int,int>mp=newDictionary<int,int>();for(inti=0;i<n;i++){mp[preMirror[i]]=i;}int[]preIndex=newint[]{0};returnbuildTree(pre,preMirror,preIndex,0,n-1,mp,n);}// Inorder traversalstaticvoidinorder(Noderoot){if(root==null)return;inorder(root.left);Console.Write(root.data+" ");inorder(root.right);}// mainstaticvoidMain(){int[]pre={1,2,4,5,3,6,7};int[]preMirror={1,3,7,6,2,5,4};Noderoot=constructBinaryTree(pre,preMirror);inorder(root);}}
JavaScript
// Definition of NodeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Recursive function to construct binary treefunctionbuildTree(pre,preMirror,preIndex,left,right,mp,n){// Base caseif(preIndex[0]>=n||left>right)returnnull;// Create current nodeletroot=newNode(pre[preIndex[0]++]);// If leaf nodeif(left===right)returnroot;// Find next preorder element index in preMirrorletmirrorIndex=mp.get(pre[preIndex[0]]);// Construct left and right subtreeif(mirrorIndex>=left&&mirrorIndex<=right){// Construct left subtreeroot.left=buildTree(pre,preMirror,preIndex,mirrorIndex,right,mp,n);// Construct right subtreeroot.right=buildTree(pre,preMirror,preIndex,left+1,mirrorIndex-1,mp,n);}returnroot;}// Wrapper function to construct binary treefunctionconstructBinaryTree(pre,preMirror){letn=pre.length;// Store indices of mirror preorder traversalletmp=newMap();for(leti=0;i<n;i++){mp.set(preMirror[i],i);}letpreIndex=[0];returnbuildTree(pre,preMirror,preIndex,0,n-1,mp,n);}// Inorder traversalfunctioninorder(root){if(!root)return;inorder(root.left);process.stdout.write(root.data+" ");inorder(root.right);}// Drive codeletpre=[1,2,4,5,3,6,7];letpreMirror=[1,3,7,6,2,5,4];letroot=constructBinaryTree(pre,preMirror);inorder(root);