
- 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
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 Articles
- Construct Binary Search Tree from Preorder Traversal in Python
- Check if a given array can represent Preorder Traversal of Binary Search Tree in C++
- Binary Tree Preorder Traversal in Python
- Binary Tree to Binary Search Tree Conversion 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 Iterator in C++
- Recover Binary Search Tree in C++
- Binary Tree Longest Consecutive Sequence in C++
- Binary Search Tree - Search and Insertion Operations in C++
- Binary Search Tree to Greater Sum Tree in C++
- Balance a Binary Search Tree in c++
- Binary Search Tree - Delete Operation in C++
- Binary Tree Longest Consecutive Sequence II in C++
- Binary Search Tree in Javascript

Advertisements