Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Stack
  • Practice Stack
  • MCQs on Stack
  • Stack Tutorial
  • Stack Operations
  • Stack Implementations
  • Monotonic Stack
  • Infix to Postfix
  • Prefix to Postfix
  • Prefix to Infix
  • Advantages & Disadvantages
Open In App
Next Article:
Check whether we can sort two arrays by swapping A[i] and B[i]
Next article icon

Check if an array can be Preorder of a BST

Last Updated : 20 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array of numbers, the task is to check if the given array can represent the preorder traversal of a Binary Search Tree.

Examples:

Input: pre[] = [40, 30, 35, 80, 100]
Output: true
Explanation: Given array can represent preorder traversal of below tree

Check-if-a-given-array-can-represent-Preorder-Traversal-of-Binary-Search-Tree


Input: pre[] = [2, 4, 1]
Output: false
Explanation: Given array cannot represent preorder traversal of a Binary Search Tree.

Table of Content

  • [Naive approach] By find next element – O(n^2) Time and O(n) Space
  • [Expected Approach – 1] Using Stack – O(n) Time and O(n) Space
  • [Expected Approach – 2] Without Using Stack – O(n) Time and O(n) Space

[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> using namespace std;  bool canRepresentBST(vector<int> &pre) {        stack<int> s;      // Initialize current root as minimum possible     // value     int root = INT_MIN;      for (int i = 0; i < pre.size(); i++) {                // If we find a node who is on right side         // and smaller than root, return false         if (pre[i] < root)             return false;          // 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]);     }     return true; }  int main() {     vector<int> pre = {40, 30, 35, 80, 100};        if (canRepresentBST(pre))         cout << "true\n";     else         cout << "false\n";      return 0; } 
Java
// Java program to check if given array can represent Preorder // traversal of a Binary Search Tree  import java.util.*;  class GfG {          static boolean canRepresentBST(List<Integer> pre) {          Stack<Integer> s = new Stack<>();          // Initialize current root as minimum possible         // value         int root = Integer.MIN_VALUE;          for (int i = 0; i < pre.size(); i++) {                        // If we find a node who is on right side             // and smaller than root, return false             if (pre.get(i) < root)                 return false;              // 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));         }         return true;     }      public static void main(String[] args) {         List<Integer> pre = Arrays.asList(40, 30, 35, 80, 100);          if (canRepresentBST(pre))             System.out.println("true");         else             System.out.println("false");     } } 
Python
# Python program to check if given array can represent Preorder # traversal of a Binary Search Tree  def canRepresentBST(pre):         s = []      # Initialize current root as minimum possible     # value     root = float('-inf')      for value in pre:                # If we find a node who is on right side         # and smaller than root, return false         if value < root:             return False          # 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 and s[-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)      return True  if __name__ == "__main__":     pre = [40, 30, 35, 80, 100]      if canRepresentBST(pre):         print("true")     else:         print("false") 
C#
// C# program to check if given array can represent Preorder // traversal of a Binary Search Tree   using System; using System.Collections.Generic;  class GfG {      static bool canRepresentBST(List<int> pre) {                  Stack<int> s = new Stack<int>();          // Initialize current root as minimum possible         // value         int root = int.MinValue;          for (int i = 0; i < pre.Count; i++) {                        // If we find a node who is on right side             // and smaller than root, return false             if (pre[i] < root)                 return false;              // 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]);         }         return true;     }     	static void Main() {         List<int> pre = new List<int>() { 40, 30, 35, 80, 100 };          if (canRepresentBST(pre))             Console.WriteLine("true");         else             Console.WriteLine("false");     } } 
JavaScript
// Javascript program to check if given array can // represent Preorder traversal of a Binary Search Tree  function canRepresentBST(pre) {      let s = [];      // Initialize current root as minimum possible     // value     let root = -Infinity;      for (let i = 0; i < pre.length; i++) {              // If we find a node who is on right side         // and smaller than root, return false         if (pre[i] < root)             return false;          // 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]);     }     return true; }  let pre = [40, 30, 35, 80, 100];  if (canRepresentBST(pre))     console.log("true"); else     console.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> using namespace std;  void buildBSThelper(int& preIndex, int n, vector<int> &pre,                      int min, int max) {      	// If we have processed all elements, return     if (preIndex >= n)         return; 	   	// If the current element lies between min and max,    	// it can be part of the BST     if (min <= pre[preIndex] && pre[preIndex] <= max) {                // Treat the current element as the root of       	// this subtree         int rootData = pre[preIndex];         preIndex++;          buildBSThelper(preIndex, n, pre, min, rootData);         buildBSThelper(preIndex, n, pre, rootData, max);     } }  bool canRepresentBST(vector<int> &arr) {      	// Set the initial min and max values     int min = INT_MIN, max = INT_MAX;      	// Start from the first element in   	// the array     int preIndex = 0;   	int n = arr.size();      buildBSThelper(preIndex, n, arr, min, max); 	   	// If all elements are processed, it means the    	// array represents a valid BST     return preIndex == n; }  int main() {      vector<int> pre = {40, 30, 35, 80, 100};     if (canRepresentBST(pre))         cout << "true\n";     else         cout << "false\n";      return 0; } 
Java
// Java program to check if a given array can represent // a preorder traversal of a BST or not  import java.util.*;  class GfG {      static void buildBSThelper(int[] preIndex, int n, List<Integer> pre,                                        int min, int max) {          // If we have processed all elements, return         if (preIndex[0] >= n)             return;          // If the current element lies between min and max,          // it can be part of the BST         if (min <= pre.get(preIndex[0]) && pre.get(preIndex[0]) <= max) {                        // Treat the current element as the root of this subtree             int rootData = 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 BST     static boolean canRepresentBST(List<Integer> arr) {          // Set the initial min and max values         int min = Integer.MIN_VALUE, max = Integer.MAX_VALUE;          // Start from the first element in the array         int[] preIndex = {0};         int n = arr.size();          buildBSThelper(preIndex, n, arr, min, max);          // If all elements are processed, it means the          // array represents a valid BST         return preIndex[0] == n;     }      public static void main(String[] args) {                List<Integer> pre = Arrays.asList(40, 30, 35, 80, 100);         if (canRepresentBST(pre))             System.out.println("true");         else             System.out.println("false");     } } 
Python
# Python program to check if a given array can represent # a preorder traversal of a BST or not  def buildBST_helper(preIndex, n, pre, min_val, max_val):        # If we have processed all elements,     # return     if preIndex[0] >= n:         return      # If the current element lies between     # min and max,      # it can be part of the BST     if min_val <= pre[preIndex[0]] <= max_val:                # Treat the current element as the root of          # this subtree         rootData = pre[preIndex[0]]         preIndex[0] += 1          buildBST_helper(preIndex, n, pre, min_val, rootData)         buildBST_helper(preIndex, n, pre, rootData, max_val)  def canRepresentBST(arr):        # Set the initial min and max values     min_val = float('-inf')     max_val = float('inf')      # Start from the first element      # in the array     preIndex = [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 BST     return preIndex[0] == n  pre = [40, 30, 35, 80, 100] if canRepresentBST(pre):     print("true") else:     print("false") 
C#
// C# program to check if a given array can represent // a preorder traversal of a BST or not  using System; using System.Collections.Generic;  class GfG {     	static void buildBSThelper(ref int preIndex, int n, List<int> pre,                                        int min, int max) {          // If we have processed all elements, return         if (preIndex >= n)             return;          // If the current element lies between min and max,          // it can be part of the BST         if (min <= pre[preIndex] && pre[preIndex] <= max) {                        // Treat the current element as the root            	// of this subtree             int rootData = pre[preIndex];             preIndex++;              buildBSThelper(ref preIndex, n, pre, min, rootData);             buildBSThelper(ref preIndex, n, pre, rootData, max);         }     }      // Function to check if the array can represent a   	// valid BST     static bool canRepresentBST(List<int> arr) {          // Set the initial min and max values         int min = int.MinValue, max = int.MaxValue;          // Start from the first element in the array         int preIndex = 0;         int n = arr.Count;          buildBSThelper(ref preIndex, n, arr, min, max);          // If all elements are processed, it means the          // array represents a valid BST         return preIndex == n;     }      static void Main(string[] args) {                List<int> pre = new List<int> {40, 30, 35, 80, 100};         if (canRepresentBST(pre))             Console.WriteLine("true");         else             Console.WriteLine("false");     } } 
JavaScript
// Javascript program to check if a given array can represent // a preorder traversal of a BST or not   function buildBSThelper(preIndex, n, pre, min, max) {      // If we have processed all elements, return     if (preIndex[0] >= n)         return;      // If the current element lies between min and max,      // it can be part of the BST     if (min <= pre[preIndex[0]] && pre[preIndex[0]] <= max) {              // Treat the current element as the root of         // this subtree         let rootData = 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 BST function canRepresentBST(arr) {      // Set the initial min and max values     let min = -Infinity, max = Infinity;      // Start from the first element in the array     let preIndex = [0];     let n = arr.length;      buildBSThelper(preIndex, n, arr, min, max);      // If all elements are processed, it means the      // array represents a valid BST     return preIndex[0] == n; }  let pre = [40, 30, 35, 80, 100];  if (canRepresentBST(pre))     console.log("true"); else     console.log("false"); 

Output
true 


Next Article
Check whether we can sort two arrays by swapping A[i] and B[i]
author
kartik
Improve
Article Tags :
  • Binary Search Tree
  • DSA
  • Stack
  • Tree
  • Adobe
  • Amazon
  • Linkedin
Practice Tags :
  • Adobe
  • Amazon
  • Linkedin
  • Binary Search Tree
  • Stack
  • Tree

Similar Reads

  • Check whether we can sort two arrays by swapping A[i] and B[i]
    Given two arrays, we have to check whether we can sort two arrays in strictly ascending order by swapping A[i] and B[i]. Examples: Input : A[ ]={ 1, 4, 3, 5, 7}, B[ ]={ 2, 2, 5, 8, 9} Output : True After swapping A[1] and B[1], both the arrays are sorted. Input : A[ ]={ 1, 4, 5, 5, 7}, B[ ]={ 2, 2,
    12 min read
  • Check if a Binary Tree is BST or not
    Given the root of a binary tree. Check whether it is a Binary Search Tree or not. A Binary Search Tree (BST) is a node-based binary tree data structure with the following properties. All keys in the left subtree are smaller than the root and all keys in the right subtree are greater.Both the left an
    15+ min read
  • Check if array can be sorted with one swap
    Given an array containing N elements. Find if it is possible to sort it in non-decreasing order using atmost one swap. Examples: Input : arr[] = {1, 2, 3, 4} Output : YES The array is already sorted Input : arr[] = {3, 2, 1} Output : YES Swap 3 and 1 to get [1, 2, 3] Input : arr[] = {4, 1, 2, 3} Out
    11 min read
  • Check if an Array is Sorted
    Given an array of size n, the task is to check if it is sorted in ascending order or not. Equal values are allowed in an array and two consecutive equal values are considered sorted. Examples: Input: arr[] = [20, 21, 45, 89, 89, 90]Output: YesInput: arr[] = [20, 20, 45, 89, 89, 90]Output: YesInput:
    9 min read
  • Check if all elements of binary array can be made 1
    Given a binary array Arr and an integer K. If the value at index i is 1 you can change 0 to 1 with in the range of ( i - K ) to ( i + K ).The task is to determine whether all the elements of the array can be made 1 or not.Examples: Input: Arr = { 0, 1, 0, 1 }, K = 2 Output: 2 Input: Arr = { 1, 0, 0,
    7 min read
  • Check if an array can be Arranged in Left or Right Positioned Array
    Given an array arr[] of size n>4, the task is to check whether the given array can be arranged in the form of Left or Right positioned array? Left or Right Positioned Array means each element in the array is equal to the number of elements to its left or number of elements to its right. Examples
    8 min read
  • Check if an Array can be Sorted by picking only the corner Array elements
    Given an array arr[] consisting of N elements, the task is to check if the given array can be sorted by picking only corner elements i.e., elements either from left or right side of the array can be chosen. Examples: Input: arr[] = {2, 3, 4, 10, 4, 3, 1} Output: Yes Explanation: The order of picking
    5 min read
  • Check if an array is Wave Array
    Given an array of N positive integers. The task is to check if the array is sorted in wave form. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: NO Input: arr[] = {1, 5, 3, 7, 2, 8, 6}Output: YES Approach: First check the element at index 1, i.e, arr[1] and observe the pattern.If arr[1] is greater t
    14 min read
  • Check if the end of the Array can be reached from a given position
    Given an array arr[] of N positive integers and a number S, the task is to reach the end of the array from index S. We can only move from current index i to index (i + arr[i]) or (i - arr[i]). If there is a way to reach the end of the array then print "Yes" else print "No". Examples: Input: arr[] =
    13 min read
  • Check whether a given array is a k sorted array or not
    Given an array of n distinct elements. Check whether the given array is a k sorted array or not. A k sorted array is an array where each element is at most k distances away from its target position in the sorted array. For example, let us consider k is 2, an element at index 7 in the sorted array, c
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
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
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences