Construct a special tree from given preorder traversal
Last Updated : 23 Jul, 2025
Given an array pre[] that represents the 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 the value ‘N’ indicates that the corresponding node is a non-leaf node. The task is to construct the tree from the given two arrays.
[Expected Approach] Using Pre-Order Traversal - O(n) Time and O(h) Space
The first element in pre[] will always be root. So we can easily figure out the root. If the left subtree is empty, the right subtree must also be empty, and the preLN[] entry for root must be ‘L’. We can simply create a node and return it. If the left and right subtrees are not empty, then recursively call for left and right subtrees and link the returned nodes to root.
C++
// C++ program to construct tree// from preorder traversal#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Recursive function to construct the treeNode*constructTreeRecur(int&index,vector<int>&pre,vector<char>&preLN){Node*root=newNode(pre[index++]);// If the current node is leaf node,// then return the node.if(preLN[index-1]=='L')returnroot;// Recursively create the left and right subtree. root->left=constructTreeRecur(index,pre,preLN);root->right=constructTreeRecur(index,pre,preLN);returnroot;}Node*constructTree(intn,vector<int>&pre,vector<char>&preLN){// base caseif(n==0)returnnullptr;intindex=0;returnconstructTreeRecur(index,pre,preLN);}voidinorder(Node*root){if(root==nullptr)return;inorder(root->left);cout<<root->data<<" ";inorder(root->right);}intmain(){vector<int>pre={10,30,20,5,15};vector<char>preLN={'N','N','L','L','L'};intn=5;Node*root=constructTree(n,pre,preLN);inorder(root);return0;}
Java
// Java program to construct tree// from preorder traversalimportjava.util.ArrayList;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Recursive function to construct the treestaticNodeconstructTreeRecur(int[]index,ArrayList<Integer>pre,ArrayList<Character>preLN){Noderoot=newNode(pre.get(index[0]++));// If the current node is leaf node,// then return the node.if(preLN.get(index[0]-1)=='L')returnroot;// Recursively create the left and right subtree.root.left=constructTreeRecur(index,pre,preLN);root.right=constructTreeRecur(index,pre,preLN);returnroot;}// Main function to construct the treestaticNodeconstructTree(intn,ArrayList<Integer>pre,ArrayList<Character>preLN){// base caseif(n==0)returnnull;int[]index={0};returnconstructTreeRecur(index,pre,preLN);}staticvoidinorder(Noderoot){if(root==null)return;inorder(root.left);System.out.print(root.data+" ");inorder(root.right);}publicstaticvoidmain(String[]args){ArrayList<Integer>pre=newArrayList<>();pre.add(10);pre.add(30);pre.add(20);pre.add(5);pre.add(15);ArrayList<Character>preLN=newArrayList<>();preLN.add('N');preLN.add('N');preLN.add('L');preLN.add('L');preLN.add('L');Noderoot=constructTree(pre.size(),pre,preLN);inorder(root);}}
Python
# Python program to construct tree# from preorder traversalclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Recursive function to construct the treedefconstructTreeRecur(index,pre,preLN):root=Node(pre[index[0]])index[0]+=1# If the current node is leaf node,# then return the node.ifpreLN[index[0]-1]=='L':returnroot# Recursively create the left and right subtree.root.left=constructTreeRecur(index,pre,preLN)root.right=constructTreeRecur(index,pre,preLN)returnrootdefconstructTree(n,pre,preLN):# base caseifn==0:returnNoneindex=[0]returnconstructTreeRecur(index,pre,preLN)definorder(root):ifrootisNone:returninorder(root.left)print(root.data,end=" ")inorder(root.right)if__name__=='__main__':pre=[10,30,20,5,15]preLN=['N','N','L','L','L']root=constructTree(len(pre),pre,preLN)inorder(root)
C#
// C# program to construct tree// from preorder traversalusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Recursive function to construct the treestaticNodeConstructTreeRecur(refintindex,List<int>pre,List<char>preLN){Noderoot=newNode(pre[index++]);// If the current node is leaf node,// then return the node.if(preLN[index-1]=='L')returnroot;// Recursively create the left and right subtree.root.left=ConstructTreeRecur(refindex,pre,preLN);root.right=ConstructTreeRecur(refindex,pre,preLN);returnroot;}staticNodeConstructTree(intn,List<int>pre,List<char>preLN){// base caseif(n==0)returnnull;intindex=0;returnConstructTreeRecur(refindex,pre,preLN);}staticvoidInorder(Noderoot){if(root==null)return;Inorder(root.left);Console.Write(root.data+" ");Inorder(root.right);}staticvoidMain(string[]args){List<int>pre=newList<int>{10,30,20,5,15};List<char>preLN=newList<char>{'N','N','L','L','L'};Noderoot=ConstructTree(pre.Count,pre,preLN);Inorder(root);}}
JavaScript
// JavaScript program to construct tree// from preorder traversalclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Recursive function to construct the treefunctionconstructTreeRecur(index,pre,preLN){letroot=newNode(pre[index[0]++]);// If the current node is leaf node,// then return the node.if(preLN[index[0]-1]==='L')returnroot;// Recursively create the left and right subtree.root.left=constructTreeRecur(index,pre,preLN);root.right=constructTreeRecur(index,pre,preLN);returnroot;}functionconstructTree(n,pre,preLN){// base caseif(n===0)returnnull;letindex=[0];returnconstructTreeRecur(index,pre,preLN);}functioninorder(root){if(root===null)return;inorder(root.left);console.log(root.data+" ");inorder(root.right);}letpre=[10,30,20,5,15];letpreLN=['N','N','L','L','L'];letroot=constructTree(pre.length,pre,preLN);inorder(root);
Output
20 30 5 10 15
[Alternate Approach] Using Stack - O(n) Time and O(h) Space
The idea is to use a stack to implement pre-order traversal and construct the binary tree and return the root node.
Step by step implementation:
As the Pre-order Traversal is given, so we first create the root node and insert it into an empty stack.
Traverse the given pre-order traversal.
Create the node corresponding to the current value.
Check the top node in the stack:
If left of top node is null, then set the current node as left of top node.
Else, right of top node is null, then set the current node as right of top node and pop the top node.
If the present node is not a leaf node, push node into the stack.
Return the root of the constructed tree.
C++
// C++ program to construct tree// from preorder traversal#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// function to construct the treeNode*constructTree(intn,vector<int>&pre,vector<char>&preLN){// base caseif(n==0)returnnullptr;stack<Node*>st;Node*root=newNode(pre[0]);// Checking if root is not leaf nodeif(preLN[0]!='L')st.push(root);// Iterating over the given node valuesfor(inti=1;i<n;i++){Node*curr=newNode(pre[i]);// Checking if the left position is // NULL or notif(!st.top()->left){st.top()->left=curr;}// Checking if the right position // is NULL or notelseif(!st.top()->right){st.top()->right=curr;st.pop();}// If current node is internal node,// then push it to stack.if(preLN[i]!='L')st.push(curr);}returnroot;}voidinorder(Node*root){if(root==nullptr)return;inorder(root->left);cout<<root->data<<" ";inorder(root->right);}intmain(){vector<int>pre={10,30,20,5,15};vector<char>preLN={'N','N','L','L','L'};intn=5;Node*root=constructTree(n,pre,preLN);inorder(root);return0;}
Java
// Java program to construct tree// from preorder traversalimportjava.util.ArrayList;importjava.util.Stack;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// function to construct the treestaticNodeconstructTree(intn,ArrayList<Integer>pre,ArrayList<Character>preLN){// base caseif(n==0)returnnull;Stack<Node>st=newStack<>();Noderoot=newNode(pre.get(0));// Checking if root is not leaf nodeif(preLN.get(0)!='L')st.push(root);// Iterating over the given node valuesfor(inti=1;i<n;i++){Nodecurr=newNode(pre.get(i));// Checking if the left position is // NULL or notif(st.peek().left==null){st.peek().left=curr;}// Checking if the right position is NULL // or notelseif(st.peek().right==null){st.peek().right=curr;st.pop();}// If current node is internal node,// then push it to stack.if(preLN.get(i)!='L')st.push(curr);}returnroot;}staticvoidinorder(Noderoot){if(root==null)return;inorder(root.left);System.out.print(root.data+" ");inorder(root.right);}publicstaticvoidmain(String[]args){ArrayList<Integer>pre=newArrayList<>();pre.add(10);pre.add(30);pre.add(20);pre.add(5);pre.add(15);ArrayList<Character>preLN=newArrayList<>();preLN.add('N');preLN.add('N');preLN.add('L');preLN.add('L');preLN.add('L');intn=pre.size();Noderoot=constructTree(n,pre,preLN);inorder(root);}}
Python
# Python program to construct tree# from preorder traversalclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# function to construct the treedefconstructTree(n,pre,preLN):# base caseifn==0:returnNonest=[]root=Node(pre[0])# Checking if root is not leaf nodeifpreLN[0]!='L':st.append(root)# Iterating over the given node valuesforiinrange(1,n):curr=Node(pre[i])# Checking if the left position is # None or notifnotst[-1].left:st[-1].left=curr# Checking if the right position is# None or notelifnotst[-1].right:st[-1].right=currst.pop()# If current node is internal node,# then push it to stack.ifpreLN[i]!='L':st.append(curr)returnrootdefinorder(root):ifrootisNone:returninorder(root.left)print(root.data,end=" ")inorder(root.right)if__name__=='__main__':pre=[10,30,20,5,15]preLN=['N','N','L','L','L']n=len(pre)root=constructTree(n,pre,preLN)inorder(root)
C#
// C# program to construct tree// from preorder traversalusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// function to construct the treestaticNodeConstructTree(intn,List<int>pre,List<char>preLN){// base caseif(n==0)returnnull;Stack<Node>st=newStack<Node>();Noderoot=newNode(pre[0]);// Checking if root is not leaf nodeif(preLN[0]!='L')st.Push(root);// Iterating over the given node valuesfor(inti=1;i<n;i++){Nodecurr=newNode(pre[i]);// Checking if the left position is// NULL or notif(st.Peek().left==null){st.Peek().left=curr;}// Checking if the right position is// NULL or notelseif(st.Peek().right==null){st.Peek().right=curr;st.Pop();}// If current node is internal node,// then push it to stack.if(preLN[i]!='L')st.Push(curr);}returnroot;}staticvoidInorder(Noderoot){if(root==null)return;Inorder(root.left);Console.Write(root.data+" ");Inorder(root.right);}staticvoidMain(string[]args){List<int>pre=newList<int>{10,30,20,5,15};List<char>preLN=newList<char>{'N','N','L','L','L'};intn=pre.Count;Noderoot=ConstructTree(n,pre,preLN);Inorder(root);}}
JavaScript
// JavaScript program to construct tree// from preorder traversalclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// function to construct the treefunctionconstructTree(n,pre,preLN){// base caseif(n===0)returnnull;letst=[];letroot=newNode(pre[0]);// Checking if root is not leaf nodeif(preLN[0]!=='L')st.push(root);// Iterating over the given node valuesfor(leti=1;i<n;i++){letcurr=newNode(pre[i]);// Checking if the left position is// NULL or notif(!st[st.length-1].left){st[st.length-1].left=curr;}// Checking if the right position is// NULL or notelseif(!st[st.length-1].right){st[st.length-1].right=curr;st.pop();}// If current node is internal node,// then push it to stack.if(preLN[i]!=='L')st.push(curr);}returnroot;}functioninorder(root){if(root===null)return;inorder(root.left);console.log(root.data+" ");inorder(root.right);}constpre=[10,30,20,5,15];constpreLN=['N','N','L','L','L'];constn=pre.length;constroot=constructTree(n,pre,preLN);inorder(root);