Before understanding this with a program let’s know some properties of BST.

  • Nodes in the left subtree of a node have keys less than the node’s key.
  • Nodes in the right subtree of a node in BST have keys greater than the node’s key.
  • Both left and right subtrees are also BST.
  • To check a binary tree is BST or not, we have different approaches like Brute Force Approach, Optimized Brute Force, and Using In order Traversal.
  • Today we will show this using the Inorder Traversal approach.

 

 

BY Best Interview Question ON 26 Feb 2022

Example

bool isBST(node* root)
 {
     static node *prev = NULL;
     if (root)
      {
        if (!isBST(root->left))
        return false;
       if (prev != NULL && root->data <= prev->data)
       return false;
       prev = root;
       return isBST(root->right);
      }
  return true;
}