
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 <iostream> #include <stack> using namespace std; bool isValidPreorder(int pre[], int n) { stack<int> stk; int root = INT_MIN; for (int i=0; i<n; i++) { if (pre[i] < root) return false; while (!stk.empty() && stk.top()<pre[i]) { root = stk.top(); stk.pop(); } stk.push(pre[i]); } return true; } int main() { int pre[] = {40, 30, 35, 80, 100}; int n = sizeof(pre)/sizeof(pre[0]); if(isValidPreorder(pre, n)) cout << "This can form BST"; else cout << "This can not form BST"; }
Output
This can form BST
- Related Articles
- Construct Binary Search Tree from Preorder Traversal in Python
- C++ Program to Perform Preorder Recursive Traversal of a Given Binary Tree
- Binary Tree Preorder Traversal in Python
- C++ Program to Perform Preorder Non-Recursive Traversal of a Given Binary Tree
- Golang Program to traverse a given binary tree in Preorder Traversal (Recursive)
- Find n-th node in Preorder traversal of a Binary Tree in C++
- Verify Preorder Sequence in Binary Search Tree in C++
- Recover a Tree From Preorder Traversal in C++
- Construct Binary Tree from Preorder and Inorder Traversal in Python
- Construct Binary Tree from Preorder and Postorder Traversal in Python
- N-ary Tree Preorder Traversal in C++
- C++ Program to Check Whether a Given Tree is Binary Search Tree
- Preorder Tree Traversal in Data Structures
- Preorder Traversal of N-ary Tree Without Recursion in C++
- Check if a given Binary Tree is SumTree in C++

Advertisements