jain12

check whether a tree is BST or not(3)

Mar 28th, 2020
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. class Node{
  5.   public:
  6.       int data;
  7.       Node *left,*right;
  8.       Node(int key){
  9.         data=key;
  10.         left=right=NULL;
  11.         }
  12.   };
  13.  
  14. int Check(Node * root,int minimum,int maximum){
  15.   if(root==NULL)
  16.      return 1;
  17.   if(minimum>root->data&& maximum<root->data)
  18.     return 0;
  19.  return Check(root->left,minimum,root->data-1) && Check(root->right,root->data+1,maximum);
  20.   }
  21.  
  22. int CheckBST(Node* root){
  23.   if(root==NULL)
  24.      return 1;
  25.   return Check(root,INT_MIN,INT_MAX);
  26.    }
  27.  
  28. void Insert(Node **root_ref,int key){
  29.   if(*root_ref==NULL){
  30.     *root_ref=new Node(key);
  31.     return;
  32.     }
  33.   if((*root_ref)->data<key)
  34.     Insert(&((*root_ref)->right),key);
  35.   else
  36.      if((*root_ref)->data>key)
  37.        Insert(&((*root_ref)->left),key);
  38.   }
  39.  
  40. int main(){
  41.  Node *root=NULL;
  42.  Insert(&root,5);
  43.  Insert(&root,7);
  44.  Insert(&root,2);
  45.  Insert(&root,8);
  46.  if(CheckBST(root))
  47.     cout<<" yes it is a BST ";
  48.  else
  49.     cout<<" no ";
  50.  }
Add Comment
Please, Sign In to add comment