Showing posts with label how to check if given tree is BST. Show all posts
Showing posts with label how to check if given tree is BST. Show all posts

Wednesday, October 7, 2015

Binary Tree is BST or not c++

#include <iostream>
#include <limits.h>
using namespace std;
struct node
{
int  data;
node *left,*right;
};

void print(node *t)
{
if(t!=NULL)
{
print(t->left);
cout<<t->data<<" ";
print(t->right);

}

}

node * create(int  a)
{
node *t=new node;
t->data=a;
t->left=t->right=NULL;
return t;
}
int isBST(node *t,int min,int max)
{
if(t==NULL)return 1;
if(t!=NULL)
{
if(t->data<min||t->data>max)
return 0;
}

return (isBST(t->left,min,t->data)&&isBST(t->right,t->data,max));
}
int main()
{
node *t=NULL;
t=create(4);
t->left=create(2);
t->right=create(1);
print(t);
if(isBST(t,INT_MIN,INT_MAX))
cout<<" BST \n";
else cout<< "not BST\n";

return 0;
}

Contributors

Translate