jain12

check whether a tree is BST or not(1)

Mar 28th, 2020
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 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 CheckBST(Node* root){
  15.    if(root==NULL)
  16.      return 1;
  17.    return((root->left==NULL||((root->left)->data<root->data&&CheckBST(root->left)))&&
  18.          (root->right==NULL||((root->right)->data>root->data&&CheckBST(root->right))));
  19.    }
  20.  
  21. void Insert(Node **root_ref,int key){
  22.   if(*root_ref==NULL){
  23.     *root_ref=new Node(key);
  24.     return;
  25.     }
  26.   if((*root_ref)->data<key)
  27.     Insert(&((*root_ref)->right),key);
  28.   else
  29.      if((*root_ref)->data>key)
  30.        Insert(&((*root_ref)->left),key);
  31.   }
  32.  
  33. int main(){
  34.  Node *root=NULL;
  35.  Insert(&root,5);
  36.  Insert(&root,7);
  37.  Insert(&root,2);
  38.  Insert(&root,8);
  39.  if(CheckBST(root))
  40.     cout<<" yes it is a BST ";
  41.  else
  42.     cout<<" no ";
  43.  }
Add Comment
Please, Sign In to add comment