
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Verify Preorder Sequence in Binary Search Tree in C++
Suppose we have a sequence of numbers; we have to check whether it is the correct preorder traversal sequence of a binary search tree. We can assume that each number in the sequence is unique. Consider the following binary search tree −
So, if the input is like [5,2,1,3,6], then the output will be true
To solve this, we will follow these steps −
itr := -1
low := -infinity
for initialize i := 0, when i < size of preorder, update (increase i by 1), do −
x := preorder[i]
if x < low, then −
return false
while (itr >= 0 and preorder[itr] < x), do −
low := preorder[itr]
(decrease itr by 1)
(increase itr by 1)
preorder[itr] := x
return true
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: bool verifyPreorder(vector<int<& preorder) { int itr = -1; int low = INT_MIN; for (int i = 0; i < preorder.size(); i++) { int x = preorder[i]; if (x < low) return false; while (itr >= 0 && preorder[itr] < x) { low = preorder[itr]; itr--; } itr++; preorder[itr] = x; } return true; } }; main(){ Solution ob; vector<int< v = {5,2,1,3,6}; cout << (ob.verifyPreorder(v)); }
Input
{5,2,1,3,6}
Output
1
- Related Questions & Answers
- Construct Binary Search Tree from Preorder Traversal in Python
- Binary Tree Preorder Traversal in Python
- Binary Tree to Binary Search Tree Conversion in C++
- Binary Search Tree Iterator in C++
- Recover Binary Search Tree in C++
- Check if a given array can represent Preorder Traversal of Binary Search Tree in C++
- Binary Tree Longest Consecutive Sequence in C++
- Preorder Successor of a Node in Binary Tree in C++
- Preorder predecessor of a Node in Binary Tree in C++
- Binary Search Tree - Search and Insertion Operations in C++
- Binary Search Tree to Greater Sum Tree in C++
- Binary Search Tree - Delete Operation in C++
- Balance a Binary Search Tree in c++
- Binary Tree Longest Consecutive Sequence II in C++
- Binary Search Tree in Javascript
Advertisements