Check if a given array can represent Preorder Traversal of Binary Search Tree in C++



In this article, we have an array of preorder traversal of a binary search tree. Our task is to check if the given array can represent the preorder traversal of the binary search tree. In preorder traversal of tree, the root node is visited first, then the left subtree, and finally the right subtree.

What is Binary Search Tree?

A binary search tree is a tree data structure and a special type of binary tree that follows the conditions given below:

  • The left child node's value is always less than the parent node.
  • The right child node has a greater value than the parent node.
  • All the nodes individually form a binary search tree.

Below are the examples to check if the given array can represent the preorder traversal of a binary search tree:

Scenario 1

Input: Array of preorder traversal: {40, 30, 35, 80, 100}
Output: true

Scenario 2

Input: Array of preorder traversal: {40, 30, 35, 20, 80, 100}
Output: false

Here is the Binary Search Tree representation of the above preorder traversal arrays:

Preorder traversal array of BST

The approaches to check if the given array can represent the preorder traversal of BST are given below:

Using Brute Force Method

In the brute force method to check if the given array can represent preorder traversal of BST, we find the first index of the node that is greater than the root. Then, from this index to the end, we check if there is any node that is less than the root node and return false if any such node exists.

  • Define a isPreorder() function that accepts the given array, the starting index, and the last index of the array.
  • First, we check if the given array is empty or has a single element, and return true as an empty or a single node tree is a binary search tree.
  • Assign the first element of the array as the root node, since in pre-order, we traverse root node first, then left, and then the right node.
  • Find the first element that is greater than the root element. Store this index as rightStart.
  • Iterate from the rightStart till the end of the array and check that all the elements should be greater than the root.
  • Recursively call the isPreorder() function from start + 1 to rightStart - 1 to check in the left subtree.
  • Recursively call the isPreorder() function from rightStart till end to check in right subtree.
  • Based on the boolean output of isPreorder() function, return whether the given array can be represented in preorder traversal or not.

Example

Here is the code implementation of the above-mentioned steps of brute force method for checking if the given array represents the preorder traversal of BST:

#include <iostream>
using namespace std;

bool isPreorder(int pre[], int start, int end)
{
    if (start >= end)
        return true;

    int root = pre[start];

    // Boundary of starting of right subtree
    int rightStart = start + 1;
    while (rightStart <= end && pre[rightStart] < root)
    {
        rightStart++;
    }

    // Check that all remaining elements are greater than root
    for (int i = rightStart; i <= end; i++)
    {
        if (pre[i] < root)
            return false; 
    }

    return isPreorder(pre, start + 1, rightStart - 1) &&
           isPreorder(pre, rightStart, end);
}

bool check(int pre[], int n)
{
    return isPreorder(pre, 0, n - 1);
}

int main()
{
    int pre[] = {40, 30, 35, 80, 100};
    int n = sizeof(pre) / sizeof(pre[0]);

    cout << "Given array of preorder traversal: ";
    for (int x : pre)
        cout << x << " ";
    cout << "\nGiven array of preorder is "
         << (check(pre, n) ? "Valid BST" : "Invalid BST")
         << endl;
}

The output of the above code is as follows:

Given array of preorder traversal: 40 30 35 80 100 
Given array of preorder is Valid BST

Using Stack

The steps for checking the preorder array for representing a BST using a stack are given below:

  • Define a check() function that accepts the given array and the size of the array.
  • Initialize a stack and a variable minValue with INT_MIN. The minValue checks the minimum valid value for the current element.
  • Iterate through the array elements to check if it is less than the minValue and return false for elements less than the minValue.
  • If stack is not empty and the top element of the stack is smaller than the current element, pop elements from the stack and update the minValue to the last popped element.
  • Push the current element to the stack.
  • After checking each array element, return true if properties of BST are maintained.

Example

Below is the implementation of the above-mentioned steps using a stack:

#include <iostream>
#include <stack>
#include <climits>
using namespace std;

bool check(int pre[], int n)
{
    stack<int> s;
    int minValue = INT_MIN;
    for (int i = 0; i < n; i++)
    {
        if (pre[i] < minValue)
            return false;
        while (!s.empty() && s.top() < pre[i])
        {
            minValue = s.top();
            s.pop();
        }
        s.push(pre[i]);
    }
    return true;
}
int main()
{
    int pre[] = {40, 30, 35, 80, 100};
    int n = sizeof(pre) / sizeof(pre[0]);
    cout << "Given array of preorder traversal: ";
    for (int i = 0; i < n; i++)
    {
        cout << pre[i] << " ";
    }
    cout << endl;
    if (check(pre, n))
        cout << "This can form BST";
    else
        cout << "This can not form BST";
}

The output of the above code is as follows:

Given array of preorder traversal: 40 30 35 80 100 
This can form BST

Complexity Comparison

Here is a comparison of the time and space complexity of all the above approaches.

Approach Time Complexity Space Complexity
Brute Force Method O(n2) O(n)
Using Stack O(n) O(n)
Updated on: 2025-08-19T17:22:30+05:30

531 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements