#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data, pointer to
left child and a pointer to right child */
struct Node {
int data;
struct Node *left, *right;
Node(int data)
{
this->data = data;
left = right = NULL;
}
};
bool isBSTUtil(struct Node* root, Node*& prev)
{
if (root) cout << "root: " << root->data;
if (prev) cout << " prev: " << prev->data;
cout << endl;
// traverse the tree in inorder fashion and
// keep track of prev node
if (root) {
if (!isBSTUtil(root->left, prev))
return false;
// Allows only distinct valued nodes
if (prev != NULL && root->data <= prev->data)
return false;
prev = root;
return isBSTUtil(root->right, prev);
}
return true;
}
bool isBSTUtil2(Node* root) {
if (root == nullptr) {
return true;
}
if (!isBSTUtil2(root->left)) {
return false;
}
if (!isBSTUtil2(root->right)) {
return false;
}
bool result = true;
if (root->left != nullptr) {
result = result && (root->data > root->left->data);
}
if (root->right != nullptr) {
result = result && (root->data < root->right->data);
}
return result;
}
bool isBST(Node* root)
{
// Node* prev = NULL;
// return isBSTUtil(root, prev);
return isBSTUtil2(root);
}
/* Driver code*/
int main()
{
struct Node* root = new Node(7);
root->left = new Node(3);
root->right = new Node(10);
root->right->left = new Node(8);
root->right->right = new Node(15);
// Function call
if (isBST(root))
cout << "Is BST";
else
cout << "Not a BST";
return 0;
}