Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <limits>
- struct Node {
- int data;
- Node* left;
- Node* right;
- Node(int val) : data(val), left(nullptr), right(nullptr) {}
- };
- bool isBSTUtil(Node* node, int min_val, int max_val) {
- if (node == nullptr) {
- return true;
- }
- if (node->data < min_val || node->data > max_val) {
- return false;
- }
- bool is_left_bst = isBSTUtil(node->left, min_val, node->data - 1);
- if (!is_left_bst) {
- return false;
- }
- bool is_right_bst = isBSTUtil(node->right, node->data, max_val);
- return is_right_bst;
- }
- bool isBinarySearchTree(Node* root) {
- return isBSTUtil(root, std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
- }
- int main() {
- Node* root = new Node(4);
- root->left = new Node(2);
- root->right = new Node(6);
- root->left->left = new Node(1);
- root->left->right = new Node(3);
- root->right->left = new Node(5);
- root->right->right = new Node(7);
- bool is_bst = isBinarySearchTree(root);
- std::cout << "The inputted data elements are structured as a: ";
- if (is_bst) {
- std::cout << "BINARY SEARCH TREE (BST)." << std::endl;
- } else {
- std::cout << "NOT a Binary Search Tree (BST)." << std::endl;
- }
- delete root->left->left;
- delete root->left->right;
- delete root->right->left;
- delete root->right->right;
- delete root->left;
- delete root->right;
- delete root;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment