
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements