Question:
Given a binary tree root node, check if it is a Binary Search Tree
Solution:
A Binary Tree is a BST if it satisfy below 2 conditions.
The node values left of the root node should always be less and
The node values right of the root node should always be higher than the root node value.
Solution in C++
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
// structure to hold binary tree node
struct Node
{
int data;
Node *left, *right;
Node(int data)
{
this->data = data;
this->left = this->right = nullptr;
}
};
Node *temp = NULL;
bool is_tree_bst(Node *node)
{
if (node == NULL)
{
return true;
}
if (!is_tree_bst(node->left))
{
return false;
}
if (temp != NULL && node->data < temp->data)
{
return false;
}
temp = node;
return is_tree_bst(node->right);
}
int main()
{
Node* root = nullptr;
/* Binary tree:
16
/ \
/ \
10 25
/ \ / \
/ \ / \
7 15 18 30
*/
root = new Node(16);
root->left = new Node(10);
root->right = new Node(25);
root->left->left = new Node(7);
root->left->right = new Node(15);
root->right->left = new Node(18);
root->right->right = new Node(30);
if (is_tree_bst(root))
{
cout<<"The binary tree is a BST"<<endl;
} else {
cout<<"The binary tree is NOT a BST"<<endl;
}
return 0;
}
Output:
The binary tree is a BST