fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct Node {
  5. int key;
  6. Node *left, *right;
  7. Node(int val) {
  8. key = val;
  9. left = NULL;
  10. right = NULL;
  11. }
  12. };
  13.  
  14. // Check for BST
  15. bool isBST(Node *root, Node *min = NULL, Node *max = NULL) {
  16. if (root == NULL)
  17. return true;
  18. if (min != NULL && root->key <= min->key) {
  19. return false;
  20. }
  21. if (max != NULL && root->key >= max->key) {
  22. return false;
  23. }
  24. bool leftValid = isBST(root->left, min, root);
  25. bool rightValid = isBST(root->right, root, max);
  26. return leftValid && rightValid;
  27. }
  28.  
  29. int main() {
  30. Node *root1 = new Node(2); // Fixing root key to 2
  31. root1->left = new Node(1); // Inserting 1 as left child
  32. root1->right = new Node(3); // Inserting 3 as right child
  33.  
  34. if (isBST(root1, NULL, NULL))
  35. cout << "Valid BST" << endl;
  36. else
  37. cout << "Invalid BST" << endl;
  38.  
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0s 5296KB
stdin
Standard input is empty
stdout
Valid BST