C++ Program To Check Whether a Given Tree is Binary Search Tree

«
»
This C++ program checks whether the nodes entered form a binary search tree, a tree consisting of only two child nodes.

Here is the source code of the C++ program to display whether the nodes given as input give a binary search tree as output or not. This C++ program is successfully compiled and run on DevCpp, a C++ compiler. The program output is given below.

  1. /*
  2.  * C++ Program To Check Whether a Given Tree is Binary Search Tree
  3.  */
  4. #include<stdio.h>
  5. #include<stdlib.h>
  6. #include<limits.h>
  7. #include<iostream>
  8. using namespace std;
  9. struct node
  10. {
  11.     int data;
  12.     struct node* left;
  13.     struct node* right;
  14. }*node1 = NULL;
  15. int isBSTUtil(struct node* node, int min, int max) 
  16. { 
  17.     if (node==NULL) 
  18.         return 1;      
  19.     if (node->data < min || node->data > max) 
  20.         return 0; 
  21.     return isBSTUtil(node->left, min, node->data-1) && isBSTUtil(node->right, node->data+1, max); 
  22. } 
  23. int isBST(struct node* node) 
  24. { 
  25.     return(isBSTUtil(node, INT_MIN, INT_MAX)); 
  26. } 
  27. struct node* newNode(int data)
  28. {
  29.     node1 = new node;
  30.     node1->data = data;
  31.     node1->left = NULL;
  32.     node1->right = NULL;
  33.     return(node);
  34. }
  35. int main()
  36. {
  37.     struct node *root = newNode(4);
  38.     root->left = newNode(2);
  39.     root->right = newNode(5);
  40.     root->left->left = newNode(1);
  41.     root->left->right = newNode(3); 
  42.  
  43.     if(isBST(root))
  44.         cout<<"Is BST";
  45.     else
  46.         cout<<"Not a BST";   
  47.     getch();
  48. }

advertisement
Output
Is BST

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn