Delta_Sierra

Binary Search C++ _Samson

Sep 30th, 2025 (edited)
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. #include <iostream>
  2. #include <limits>
  3.  
  4. struct Node {
  5.     int data;
  6.     Node* left;
  7.     Node* right;
  8.     Node(int val) : data(val), left(nullptr), right(nullptr) {}
  9. };
  10.  
  11. bool isBSTUtil(Node* node, int min_val, int max_val) {
  12.     if (node == nullptr) {
  13.         return true;
  14.     }
  15.  
  16.     if (node->data < min_val || node->data > max_val) {
  17.         return false;
  18.     }
  19.  
  20.     bool is_left_bst = isBSTUtil(node->left, min_val, node->data - 1);
  21.     if (!is_left_bst) {
  22.         return false;
  23.     }
  24.  
  25.     bool is_right_bst = isBSTUtil(node->right, node->data, max_val);
  26.    
  27.     return is_right_bst;
  28. }
  29.  
  30. bool isBinarySearchTree(Node* root) {
  31.     return isBSTUtil(root, std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
  32. }
  33.  
  34. int main() {
  35.     Node* root = new Node(4);
  36.    
  37.     root->left = new Node(2);
  38.     root->right = new Node(6);
  39.    
  40.     root->left->left = new Node(1);
  41.     root->left->right = new Node(3);
  42.    
  43.     root->right->left = new Node(5);
  44.     root->right->right = new Node(7);
  45.  
  46.     bool is_bst = isBinarySearchTree(root);
  47.  
  48.     std::cout << "The inputted data elements are structured as a: ";
  49.     if (is_bst) {
  50.         std::cout << "BINARY SEARCH TREE (BST)." << std::endl;
  51.     } else {
  52.         std::cout << "NOT a Binary Search Tree (BST)." << std::endl;
  53.     }
  54.    
  55.     delete root->left->left;
  56.     delete root->left->right;
  57.     delete root->right->left;
  58.     delete root->right->right;
  59.     delete root->left;
  60.     delete root->right;
  61.     delete root;
  62.  
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment