[Naive approach] By find next element - O(n^2) Time and O(n) Space
The idea is to search for next greater element for every pre[i] starting from first one. Here below steps that can be follow for this approach:
Find the first greater value on right side of current node. Let the index of this node be j.
Return true if following conditions hold. Else return false.
All values after the above found greater value are greater than current node.
Recursive calls for the subarrays pre[i+1..j-1] and pre[j+1..n-1] also return true.
The Time complexity for this approach is O(n ^ 2) where n is the number of elements in pre order.
[Expected Approach - 1] Using Stack - O(n) Time and O(n) Space
The idea is to use a stack. This problem is similar to Next (or closest) Greater Element problem. Here we find the next greater element and after finding next greater, if we find a smaller element, then return false.
Follow the steps below to solve the problem:
Start with the smallest possible value as the root and an empty stack.
Iterate through the array. If the current element is smaller than the root, return false (violates the BST property).
For each element:
If it is smaller than the stack's top, it belongs to the left subtree. Push it onto the stack.
If it is larger, it belongs to the right subtree. Pop elements from the stack (moving up the tree) until the top is larger than the current element, updating the root with the last popped value. Push the current element onto the stack.
If the loop completes without violations, the array represents a valid BST preorder traversal.
C++
// C++ program to check if given array can represent Preorder// traversal of a Binary Search Tree#include<bits/stdc++.h>usingnamespacestd;boolcanRepresentBST(vector<int>&pre){stack<int>s;// Initialize current root as minimum possible// valueintroot=INT_MIN;for(inti=0;i<pre.size();i++){// If we find a node who is on right side// and smaller than root, return falseif(pre[i]<root)returnfalse;// If pre[i] is in right subtree of stack top,// Keep removing items smaller than pre[i]// and make the last removed item as new// root.while(!s.empty()&&s.top()<pre[i]){root=s.top();s.pop();}// At this point either stack is empty or// pre[i] is smaller than root, push pre[i]s.push(pre[i]);}returntrue;}intmain(){vector<int>pre={40,30,35,80,100};if(canRepresentBST(pre))cout<<"true\n";elsecout<<"false\n";return0;}
Java
// Java program to check if given array can represent Preorder// traversal of a Binary Search Treeimportjava.util.*;classGfG{staticbooleancanRepresentBST(List<Integer>pre){Stack<Integer>s=newStack<>();// Initialize current root as minimum possible// valueintroot=Integer.MIN_VALUE;for(inti=0;i<pre.size();i++){// If we find a node who is on right side// and smaller than root, return falseif(pre.get(i)<root)returnfalse;// If pre[i] is in right subtree of stack top,// Keep removing items smaller than pre[i]// and make the last removed item as new// root.while(!s.isEmpty()&&s.peek()<pre.get(i)){root=s.pop();}// At this point either stack is empty or// pre[i] is smaller than root, push pre[i]s.push(pre.get(i));}returntrue;}publicstaticvoidmain(String[]args){List<Integer>pre=Arrays.asList(40,30,35,80,100);if(canRepresentBST(pre))System.out.println("true");elseSystem.out.println("false");}}
Python
# Python program to check if given array can represent Preorder# traversal of a Binary Search TreedefcanRepresentBST(pre):s=[]# Initialize current root as minimum possible# valueroot=float('-inf')forvalueinpre:# If we find a node who is on right side# and smaller than root, return falseifvalue<root:returnFalse# If pre[i] is in right subtree of stack top,# Keep removing items smaller than pre[i]# and make the last removed item as new# root.whilesands[-1]<value:root=s.pop()# At this point either stack is empty or# pre[i] is smaller than root, push pre[i]s.append(value)returnTrueif__name__=="__main__":pre=[40,30,35,80,100]ifcanRepresentBST(pre):print("true")else:print("false")
C#
// C# program to check if given array can represent Preorder// traversal of a Binary Search TreeusingSystem;usingSystem.Collections.Generic;classGfG{staticboolcanRepresentBST(List<int>pre){Stack<int>s=newStack<int>();// Initialize current root as minimum possible// valueintroot=int.MinValue;for(inti=0;i<pre.Count;i++){// If we find a node who is on right side// and smaller than root, return falseif(pre[i]<root)returnfalse;// If pre[i] is in right subtree of stack top,// Keep removing items smaller than pre[i]// and make the last removed item as new// root.while(s.Count>0&&s.Peek()<pre[i]){root=s.Pop();}// At this point either stack is empty or// pre[i] is smaller than root, push pre[i]s.Push(pre[i]);}returntrue;}staticvoidMain(){List<int>pre=newList<int>(){40,30,35,80,100};if(canRepresentBST(pre))Console.WriteLine("true");elseConsole.WriteLine("false");}}
JavaScript
// Javascript program to check if given array can// represent Preorder traversal of a Binary Search TreefunctioncanRepresentBST(pre){lets=[];// Initialize current root as minimum possible// valueletroot=-Infinity;for(leti=0;i<pre.length;i++){// If we find a node who is on right side// and smaller than root, return falseif(pre[i]<root)returnfalse;// If pre[i] is in right subtree of stack top,// Keep removing items smaller than pre[i]// and make the last removed item as new// root.while(s.length>0&&s[s.length-1]<pre[i]){root=s.pop();}// At this point either stack is empty or// pre[i] is smaller than root, push pre[i]s.push(pre[i]);}returntrue;}letpre=[40,30,35,80,100];if(canRepresentBST(pre))console.log("true");elseconsole.log("false");
Output
true
[Expected Approach - 2] Without Using Stack - O(n) Time and O(n) Space
We can check if the given preorder traversal is valid or not for a BST without using stack. The idea is to use the similar concept of Building a BST using narrowing bound algorithm. We will recursively visit all nodes, but we will not build the nodes. In the end, if the complete array is not traversed, then that means that array can not represent the preorder traversal of any binary tree.
C++
// C++ program to check if a given array can represent// a preorder traversal of a BST or not#include<bits/stdc++.h>usingnamespacestd;voidbuildBSThelper(int&preIndex,intn,vector<int>&pre,intmin,intmax){// If we have processed all elements, returnif(preIndex>=n)return;// If the current element lies between min and max, // it can be part of the BSTif(min<=pre[preIndex]&&pre[preIndex]<=max){// Treat the current element as the root of // this subtreeintrootData=pre[preIndex];preIndex++;buildBSThelper(preIndex,n,pre,min,rootData);buildBSThelper(preIndex,n,pre,rootData,max);}}boolcanRepresentBST(vector<int>&arr){// Set the initial min and max valuesintmin=INT_MIN,max=INT_MAX;// Start from the first element in// the arrayintpreIndex=0;intn=arr.size();buildBSThelper(preIndex,n,arr,min,max);// If all elements are processed, it means the // array represents a valid BSTreturnpreIndex==n;}intmain(){vector<int>pre={40,30,35,80,100};if(canRepresentBST(pre))cout<<"true\n";elsecout<<"false\n";return0;}
Java
// Java program to check if a given array can represent// a preorder traversal of a BST or notimportjava.util.*;classGfG{staticvoidbuildBSThelper(int[]preIndex,intn,List<Integer>pre,intmin,intmax){// If we have processed all elements, returnif(preIndex[0]>=n)return;// If the current element lies between min and max, // it can be part of the BSTif(min<=pre.get(preIndex[0])&&pre.get(preIndex[0])<=max){// Treat the current element as the root of this subtreeintrootData=pre.get(preIndex[0]);preIndex[0]++;buildBSThelper(preIndex,n,pre,min,rootData);buildBSThelper(preIndex,n,pre,rootData,max);}}// Function to check if the array can represent a // valid BSTstaticbooleancanRepresentBST(List<Integer>arr){// Set the initial min and max valuesintmin=Integer.MIN_VALUE,max=Integer.MAX_VALUE;// Start from the first element in the arrayint[]preIndex={0};intn=arr.size();buildBSThelper(preIndex,n,arr,min,max);// If all elements are processed, it means the // array represents a valid BSTreturnpreIndex[0]==n;}publicstaticvoidmain(String[]args){List<Integer>pre=Arrays.asList(40,30,35,80,100);if(canRepresentBST(pre))System.out.println("true");elseSystem.out.println("false");}}
Python
# Python program to check if a given array can represent# a preorder traversal of a BST or notdefbuildBST_helper(preIndex,n,pre,min_val,max_val):# If we have processed all elements,# returnifpreIndex[0]>=n:return# If the current element lies between# min and max, # it can be part of the BSTifmin_val<=pre[preIndex[0]]<=max_val:# Treat the current element as the root of # this subtreerootData=pre[preIndex[0]]preIndex[0]+=1buildBST_helper(preIndex,n,pre,min_val,rootData)buildBST_helper(preIndex,n,pre,rootData,max_val)defcanRepresentBST(arr):# Set the initial min and max valuesmin_val=float('-inf')max_val=float('inf')# Start from the first element # in the arraypreIndex=[0]n=len(arr)buildBST_helper(preIndex,n,arr,min_val,max_val)# If all elements are processed, it means the # array represents a valid BSTreturnpreIndex[0]==npre=[40,30,35,80,100]ifcanRepresentBST(pre):print("true")else:print("false")
C#
// C# program to check if a given array can represent// a preorder traversal of a BST or notusingSystem;usingSystem.Collections.Generic;classGfG{staticvoidbuildBSThelper(refintpreIndex,intn,List<int>pre,intmin,intmax){// If we have processed all elements, returnif(preIndex>=n)return;// If the current element lies between min and max, // it can be part of the BSTif(min<=pre[preIndex]&&pre[preIndex]<=max){// Treat the current element as the root // of this subtreeintrootData=pre[preIndex];preIndex++;buildBSThelper(refpreIndex,n,pre,min,rootData);buildBSThelper(refpreIndex,n,pre,rootData,max);}}// Function to check if the array can represent a// valid BSTstaticboolcanRepresentBST(List<int>arr){// Set the initial min and max valuesintmin=int.MinValue,max=int.MaxValue;// Start from the first element in the arrayintpreIndex=0;intn=arr.Count;buildBSThelper(refpreIndex,n,arr,min,max);// If all elements are processed, it means the // array represents a valid BSTreturnpreIndex==n;}staticvoidMain(string[]args){List<int>pre=newList<int>{40,30,35,80,100};if(canRepresentBST(pre))Console.WriteLine("true");elseConsole.WriteLine("false");}}
JavaScript
// Javascript program to check if a given array can represent// a preorder traversal of a BST or notfunctionbuildBSThelper(preIndex,n,pre,min,max){// If we have processed all elements, returnif(preIndex[0]>=n)return;// If the current element lies between min and max, // it can be part of the BSTif(min<=pre[preIndex[0]]&&pre[preIndex[0]]<=max){// Treat the current element as the root of// this subtreeletrootData=pre[preIndex[0]];preIndex[0]++;buildBSThelper(preIndex,n,pre,min,rootData);buildBSThelper(preIndex,n,pre,rootData,max);}}// Function to check if the array can represent a valid BSTfunctioncanRepresentBST(arr){// Set the initial min and max valuesletmin=-Infinity,max=Infinity;// Start from the first element in the arrayletpreIndex=[0];letn=arr.length;buildBSThelper(preIndex,n,arr,min,max);// If all elements are processed, it means the // array represents a valid BSTreturnpreIndex[0]==n;}letpre=[40,30,35,80,100];if(canRepresentBST(pre))console.log("true");elseconsole.log("false");
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.