
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 Given Array Can Represent BST of N Levels in C++
We have an array A, we have to check whether the array can represent a BST with n levels or not. As the level is , we can construct a tree in following manner. Assume a number is k, value greater than k moves to right side, and less than k moves to left side. Suppose two lists are there: {50, 20, 9, 25, 10}, and {50, 30, 20, 25, 10}
The first one is not valid, but the second one is valid.
To check this we can either create a BST and check the height, otherwise use array based approach. The array based approach is like below −
- Take two variable max = infinity, to mark max limit of left subtree, and min = negative infinity to mark the minimum limit for the right subtree
- for each element in range arr[i] to arr[n – 1], repeat following steps
- if arr[i] > arr[i - 1] and arr[i] > min and arr[i] < max, then update min := arr[i – 1]
- otherwise if arr[i] > min and arr[i] < max, then update max := arr[i]
- if none of these are valid, then element will be inserted into a new level, so break
Example
#include <iostream> using namespace std; bool canMakeBSTifHeightN(int arr[], int n) { int min = INT_MIN; int max = INT_MAX; for(int i = 1; i < n; i++){ if (arr[i] > arr[i - 1] && arr[i] > min && arr[i] < max) { min = arr[i - 1]; } else if (arr[i] < arr[i - 1] && arr[i] > min && arr[i] < max) { max = arr[i - 1]; } else { return true; } } return false; } int main() { int elements[] = {50, 30, 20, 25, 10}; int n = sizeof(elements)/sizeof(elements[0]); if (canMakeBSTifHeightN(elements, n)) cout << "We can make BST of height " << n; else cout << "We can not make BST of height " << n; }
Output
We can make BST of height 5
Advertisements