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



Suppose we have a list of elements in an array, we have to check, whether the elements can be the preorder traversal of a binary search tree or not. Suppose a sequence is like {40, 30, 35, 80, 100}, then the tree will be like −

We can solve this using a stack. We have to follow these steps to solve this problem.

  • Define empty stack
  • set root as negative infinity
  • for every element in preorder sequence, do the following −
    • if the element is smaller than current root, return false
    • Keep removing elements from stack while the element is greater than stack top, and make the lastly removed element as root.
    • push the element into stack

Example

#include 
#include 
using namespace std;
bool isValidPreorder(int pre[], int n) {
   stack stk;
   int root = INT_MIN;
   for (int i=0; i

Output

This can form BST
Updated on: 2019-10-22T11:01:12+05:30

505 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements