Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a new c++ file for check is it BST or not #80

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions Bst.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
//code link:-https://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/

//A program to check if a binary tree is BST or not

#include <bits/stdc++.h>
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);

// Function call
if (isBST(root))
cout << "Is BST";
else
cout << "Not a BST";

return 0;
}

// This code is contributed by rathbhupendra