[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++
#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 a leaf node, return it directlyif(preLN[index-1]=='L')returnroot;// recursively create the left and right subtreeroot->left=constructTreeRecur(index,pre,preLN);root->right=constructTreeRecur(index,pre,preLN);returnroot;}Node*constructTree(vector<int>&pre,vector<char>&preLN){intn=pre.size();// 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'};Node*root=constructTree(pre,preLN);inorder(root);return0;}
Java
importjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGFG{staticintindex;// recursive function to construct the treestaticNodeconstructTreeRecur(List<Integer>pre,List<Character>preLN){Noderoot=newNode(pre.get(index++));// if the current node is a leaf node, return it directlyif(preLN.get(index-1)=='L')returnroot;// recursively create the left and right subtreeroot.left=constructTreeRecur(pre,preLN);root.right=constructTreeRecur(pre,preLN);returnroot;}staticNodeconstructTree(List<Integer>pre,List<Character>preLN){intn=pre.size();// base caseif(n==0)returnnull;index=0;returnconstructTreeRecur(pre,preLN);}staticvoidinorder(Noderoot){if(root==null)return;inorder(root.left);System.out.print(root.data+" ");inorder(root.right);}publicstaticvoidmain(String[]args){List<Integer>pre=Arrays.asList(10,30,20,5,15);List<Character>preLN=Arrays.asList('N','N','L','L','L');Noderoot=constructTree(pre,preLN);inorder(root);}}
Python
classNode:def__init__(self,x):self.data=xself.left=Noneself.right=Noneindex=0defconstructTreeRecur(pre,preLN):globalindexroot=Node(pre[index])index+=1# if the current node is a leaf node, return it directlyifpreLN[index-1]=='L':returnroot# recursively create the left and right subtreeroot.left=constructTreeRecur(pre,preLN)root.right=constructTreeRecur(pre,preLN)returnrootdefconstructTree(pre,preLN):globalindexn=len(pre)# base caseifn==0:returnNoneindex=0returnconstructTreeRecur(pre,preLN)definorder(root):ifrootisNone:returninorder(root.left)print(root.data,end=" ")inorder(root.right)pre=[10,30,20,5,15]preLN=['N','N','L','L','L']root=constructTree(pre,preLN)inorder(root)
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGFG{staticintindex;// recursive function to construct the treestaticNodeconstructTreeRecur(List<int>pre,List<char>preLN){Noderoot=newNode(pre[index]);index++;// if the current node is a leaf node, return it directlyif(preLN[index-1]=='L')returnroot;// recursively create the left and right subtreeroot.left=constructTreeRecur(pre,preLN);root.right=constructTreeRecur(pre,preLN);returnroot;}staticNodeconstructTree(List<int>pre,List<char>preLN){intn=pre.Count;// base caseif(n==0)returnnull;index=0;returnconstructTreeRecur(pre,preLN);}staticvoidInorder(Noderoot){if(root==null)return;Inorder(root.left);Console.Write(root.data+" ");Inorder(root.right);}staticvoidMain(){List<int>pre=newList<int>{10,30,20,5,15};List<char>preLN=newList<char>{'N','N','L','L','L'};Noderoot=constructTree(pre,preLN);Inorder(root);}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}classGFG{// recursive function to construct the treeconstructTreeRecur(pre,preLN,state){constroot=newNode(pre[state.index]);state.index++;// if the current node is a leaf node, return it directlyif(preLN[state.index-1]==='L')returnroot;// recursively create the left and right subtreeroot.left=this.constructTreeRecur(pre,preLN,state);root.right=this.constructTreeRecur(pre,preLN,state);returnroot;}constructTree(pre,preLN){constn=pre.length;// base caseif(n===0)returnnull;conststate={index:0};returnthis.constructTreeRecur(pre,preLN,state);}inorder(root){if(root===null)return;this.inorder(root.left);process.stdout.write(root.data+" ");this.inorder(root.right);}}// Driver Codeconstpre=[10,30,20,5,15];constpreLN=['N','N','L','L','L'];constgfg=newGfG();constroot=gfg.constructTree(pre,preLN);gfg.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 Preorder traversal and construct the binary tree and return the root node.
Steps
Step 1: Create the rootnode from first element and insert it into an empty stack.
Step 2: Traverse the remainingpreorder 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.
Step 3: Return the rootof the constructed tree.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};Node*constructTree(vector<int>&pre,vector<char>&preLN){intn=pre.size();// base caseif(n==0)returnnullptr;stack<Node*>st;Node*root=newNode(pre[0]);// checking if root is not a 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 nullif(!st.top()->left){st.top()->left=curr;}// checking if the right position is nullelseif(!st.top()->right){st.top()->right=curr;st.pop();}// if current node is an internal node, push it to the stackif(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'};Node*root=constructTree(pre,preLN);inorder(root);return0;}
Java
importjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGFG{staticNodeconstructTree(List<Integer>pre,List<Character>preLN){intn=pre.size();// base caseif(n==0)returnnull;Stack<Node>st=newStack<>();Noderoot=newNode(pre.get(0));// checking if root is not a 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 nullif(st.peek().left==null){st.peek().left=curr;}// checking if the right position is nullelseif(st.peek().right==null){st.peek().right=curr;st.pop();}// if current node is an internal node, push it to the stackif(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){List<Integer>pre=Arrays.asList(10,30,20,5,15);List<Character>preLN=Arrays.asList('N','N','L','L','L');Noderoot=constructTree(pre,preLN);inorder(root);}}
Python
classNode:def__init__(self,x):self.data=xself.left=Noneself.right=NonedefconstructTree(pre,preLN):n=len(pre)# base caseifn==0:returnNonest=[]root=Node(pre[0])# checking if root is not a 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 nullifst[-1].leftisNone:st[-1].left=curr# checking if the right position is nullelifst[-1].rightisNone:st[-1].right=currst.pop()# if current node is an internal node, push it to the stackifpreLN[i]!='L':st.append(curr)returnrootdefinorder(root):ifrootisNone:returninorder(root.left)print(root.data,end=" ")inorder(root.right)pre=[10,30,20,5,15]preLN=['N','N','L','L','L']root=constructTree(pre,preLN)inorder(root)
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGFG{staticNodeconstructTree(List<int>pre,List<char>preLN){intn=pre.Count;// base caseif(n==0)returnnull;Stack<Node>st=newStack<Node>();Noderoot=newNode(pre[0]);// checking if root is not a 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 nullif(st.Peek().left==null){st.Peek().left=curr;}// checking if the right position is nullelseif(st.Peek().right==null){st.Peek().right=curr;st.Pop();}// if current node is an internal node, push it to the stackif(preLN[i]!='L')st.Push(curr);}returnroot;}staticvoidinorder(Noderoot){if(root==null)return;inorder(root.left);Console.Write(root.data+" ");inorder(root.right);}staticvoidMain(){List<int>pre=newList<int>{10,30,20,5,15};List<char>preLN=newList<char>{'N','N','L','L','L'};Noderoot=constructTree(pre,preLN);inorder(root);}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}functionconstructTree(pre,preLN){constn=pre.length;// base caseif(n===0)returnnull;constst=[];constroot=newNode(pre[0]);// checking if root is not a leaf nodeif(preLN[0]!=='L')st.push(root);// iterating over the given node valuesfor(leti=1;i<n;i++){constcurr=newNode(pre[i]);// checking if the left position is nullif(st[st.length-1].left===null){st[st.length-1].left=curr;}// checking if the right position is nullelseif(st[st.length-1].right===null){st[st.length-1].right=curr;st.pop();}// if current node is an internal node, push it to the stackif(preLN[i]!=='L')st.push(curr);}returnroot;}// Driver Codefunctioninorder(root){if(root===null)return;inorder(root.left);process.stdout.write(root.data+" ");inorder(root.right);}constpre=[10,30,20,5,15];constpreLN=['N','N','L','L','L'];constroot=constructTree(pre,preLN);inorder(root);