From 1b532aec48f67d4348e7437a8a52c9c16592bb71 Mon Sep 17 00:00:00 2001 From: Harshit Jain Date: Sun, 17 Oct 2021 19:30:26 +0530 Subject: [PATCH] Create is_tree_bst.cpp --- is_tree_bst.cpp | 75 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 is_tree_bst.cpp diff --git a/is_tree_bst.cpp b/is_tree_bst.cpp new file mode 100644 index 0000000..61997fb --- /dev/null +++ b/is_tree_bst.cpp @@ -0,0 +1,75 @@ +#include + +using namespace std; + +/* A binary tree node has data, +pointer to left child and +a pointer to right child */ +class node +{ + public: + int data; + node* left; + node* right; + + /* Constructor that allocates + a new node with the given data + and NULL left and right pointers. */ + node(int data) + { + this->data = data; + this->left = NULL; + this->right = NULL; + } +}; + +int isBSTUtil(node* node, int min, int max); + +/* Returns true if the given +tree is a binary search tree +(efficient version). */ +int isBST(node* node) +{ + return(isBSTUtil(node, INT_MIN, INT_MAX)); +} + +/* Returns true if the given +tree is a BST and its values +are >= min and <= max. */ +int isBSTUtil(node* node, int min, int max) +{ + /* an empty tree is BST */ + if (node==NULL) + return 1; + + /* false if this node violates + the min/max constraint */ + if (node->data < min || node->data > max) + return 0; + + /* otherwise check the subtrees recursively, + tightening the min or max constraint */ + return + isBSTUtil(node->left, min, node->data-1) && // Allow only distinct values + isBSTUtil(node->right, node->data+1, max); // Allow only distinct values +} + + +/* Driver code*/ +int main() +{ + node *root = new node(4); + root->left = new node(2); + root->right = new node(5); + root->left->left = new node(1); + root->left->right = new node(3); + + if(isBST(root)) + cout<<"Is BST"; + else + cout<<"Not a BST"; + + return 0; +} + +// This code is contributed by rathbhupendra