A program to check if a binary tree is BST or not in C ?


A binary tree is a tree data structure in which there are two child nodes for each node. The child nodes being two are referred as, left and right child.

A BST is a tree structure in which left subtree contains nodes with values lesser than root and right subtree contains nodes with values greater that root.

Here, we will check if a binary tree is a BST or not −

To check for this we have to check for the BST condition on the binary tree. For a root node check for left child should be less that root, right child should be greater that root for all nodes of the tree in which the child's exist.

PROGRAM TO CHECK IF A BINARY TREE IS A BST

#include<bits/stdc++.h>
#include<iostream>
using namespace std;
class node {
   public:
      int data;
   node* left;
   node* right;
   node(int data) {
      this->data = data;
      this->left = NULL;
      this->right = NULL;
   }
};
int isBSTUtil(node* node, int min, int max);
int isBST(node* node) {
   return(isBSTUtil(node, INT_MIN, INT_MAX));
}
int isBSTUtil(node* node, int min, int max) {
   if (node==NULL)
      return 1;
   if (node->data < min || node->data > max)
      return 0;
   return
      isBSTUtil(node->left, min, node->data-1) && isBSTUtil(node->right, node->data+1, max);
}
int main() {
   node *root = new node(8);
   root->left = new node(3);
   root->right = new node(10);
   root->left->left = new node(1);
   root->left->right = new node(6);
   if(isBST(root))
      cout<<"The given tree is a BST";
   else
      cout<<"The given tree is Not a BST";
   return 0;
}

Output

The given tree is a BST

Code Explained

The above code check for a BST. The main method, creates a tree and call the isBST() method. This method checks if the left and right child follow the BST rule also that the subtrees formed are BST’s too by using the isBSTuntil() method.

raja
Published on 07-Aug-2019 17:59:22
Advertisements