Skip to content
Related Articles

Related Articles

A program to check if a Binary Tree is BST or not

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 11 Nov, 2022
Improve Article
Save Article

A binary search tree (BST) is a node-based binary tree data structure that has the following properties. 

  • The left subtree of a node contains only nodes with keys less than the node’s key.
  • The right subtree of a node contains only nodes with keys greater than the node’s key.
  • Both the left and right subtrees must also be binary search trees.
  • Each node (item in the tree) has a distinct key.
Change

BST

Recommended Practice

Naive Approach:

The idea is to for each node, check if max value in left subtree is smaller than the node and min value in right subtree greater than the node. 

Follow the below steps to solve the problem:

  • If the current node is null then return true
  • If the value of the left child of the node is greater than or equal to the current node then return false
  • If the value of the right child of the node is less than or equal to the current node then return false
  • If the left subtree or the right subtree is not a BST then return false
  • Else return true

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node {
    int data;
    struct node* left;
    struct node* right;
};
 
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
    struct node* node
        = (struct node*)malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
 
    return (node);
}
 
int maxValue(struct node* node)
{
    if (node == NULL) {
        return INT16_MIN;
    }
    int value = node->data;
    int leftMax = maxValue(node->left);
    int rightMax = maxValue(node->right);
 
    return max(value, max(leftMax, rightMax));
}
 
int minValue(struct node* node)
{
    if (node == NULL) {
        return INT16_MAX;
    }
    int value = node->data;
    int leftMax = minValue(node->left);
    int rightMax = minValue(node->right);
 
    return min(value, min(leftMax, rightMax));
}
 
/* Returns true if a binary tree is a binary search tree */
int isBST(struct node* node)
{
    if (node == NULL)
        return 1;
 
    /* false if the max of the left is > than us */
    if (node->left != NULL
        && maxValue(node->left) > node->data)
        return 0;
 
    /* false if the min of the right is <= than us */
    if (node->right != NULL
        && minValue(node->right) < node->data)
        return 0;
 
    /* false if, recursively, the left or right is not a BST
     */
    if (!isBST(node->left) || !isBST(node->right))
        return 0;
 
    /* passing all that, it's a BST */
    return 1;
}
 
/* Driver code*/
int main()
{
    struct node* root = newNode(4);
    root->left = newNode(2);
    root->right = newNode(5);
   // root->right->left = newNode(7);
    root->left->left = newNode(1);
    root->left->right = newNode(3);
 
    // Function call
    if (isBST(root))
        printf("Is BST");
    else
        printf("Not a BST");
 
    return 0;
}
// this code rectify by Laijyour Luv

C




#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
 
/* A binary tree node has data, pointer to left child
   and a pointer to right child */
struct node {
    int data;
    struct node* left;
    struct node* right;
};
 
/* Helper function that allocates a new node with the
   given data and NULL left and right pointers. */
struct node* newNode(int data)
{
    struct node* node
        = (struct node*)malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
 
    return (node);
}
 
int maxValue(struct node* node)
{
    if (node == NULL) {
        return 0;
    }
 
    int leftMax = maxValue(node->left);
    int rightMax = maxValue(node->right);
 
    int value = 0;
    if (leftMax > rightMax) {
        value = leftMax;
    }
    else {
        value = rightMax;
    }
 
    if (value > node->data) {
        value = node->data;
    }
 
    return value;
}
 
int minValue(struct node* node)
{
    if (node == NULL) {
        return 1000000000;
    }
 
    int leftMax = minValue(node->left);
    int rightMax = minValue(node->right);
 
    int value = 0;
    if (leftMax < rightMax) {
        value = leftMax;
    }
    else {
        value = rightMax;
    }
 
    if (value < node->data) {
        value = node->data;
    }
 
    return value;
}
 
/* Returns true if a binary tree is a binary search tree */
int isBST(struct node* node)
{
    if (node == NULL)
        return 1;
 
    /* false if the max of the left is > than us */
    if (node->left != NULL
        && maxValue(node->left) > node->data)
        return 0;
 
    /* false if the min of the right is <= than us */
    if (node->right != NULL
        && minValue(node->right) < node->data)
        return 0;
 
    /* false if, recursively, the left or right is not a BST
     */
    if (!isBST(node->left) || !isBST(node->right))
        return 0;
 
    /* passing all that, it's a BST */
    return 1;
}
 
/* Driver code*/
int main()
{
    struct node* root = newNode(4);
    root->left = newNode(2);
    root->right = newNode(5);
    root->left->left = newNode(1);
    root->left->right = newNode(3);
 
    // Function call
    if (isBST(root))
        printf("Is BST");
    else
        printf("Not a BST");
 
    getchar();
    return 0;
}

Java




// Java implementation for the above approach
import java.io.*;
 
class GFG {
 
  /* A binary tree node has data, pointer to left child
        and a pointer to right child */
  static class node {
    int data;
    node left, right;
  }
 
  /* Helper function that allocates a new node with the
        given data and NULL left and right pointers. */
  static node newNode(int data)
  {
    node Node = new node();
    Node.data = data;
    Node.left = Node.right = null;
 
    return Node;
  }
 
  static int maxValue(node Node)
  {
    if (Node == null) {
      return Integer.MIN_VALUE;
    }
    int value = Node.data;
    int leftMax = maxValue(Node.left);
    int rightMax = maxValue(Node.right);
 
    return Math.max(value, Math.max(leftMax, rightMax));
  }
 
  static int minValue(node Node)
  {
    if (Node == null) {
      return Integer.MAX_VALUE;
    }
    int value = Node.data;
    int leftMax = minValue(Node.left);
    int rightMax = minValue(Node.right);
 
    return Math.min(value, Math.min(leftMax, rightMax));
  }
 
  /* Returns true if a binary tree is a binary search tree
     */
  static int isBST(node Node)
  {
    if (Node == null) {
      return 1;
    }
     
    /* false if the max of the left is > than us */
    if (Node.left != null
        && maxValue(Node.left) > Node.data) {
      return 0;
    }
     
    /* false if the min of the right is <= than us */
    if (Node.right != null
        && minValue(Node.right) < Node.data) {
      return 0;
    }
     
    /* false if, recursively, the left or right is not a
         * BST*/
    if (isBST(Node.left) != 1
        || isBST(Node.right) != 1) {
      return 0;
    }
     
    /* passing all that, it's a BST */
    return 1;
  }
 
  public static void main(String[] args)
  {
    node root = newNode(4);
    root.left = newNode(2);
    root.right = newNode(5);
     
    // root->right->left = newNode(7);
    root.left.left = newNode(1);
    root.left.right = newNode(3);
 
    // Function call
    if (isBST(root) == 1) {
      System.out.print("Is BST");
    }
    else {
      System.out.print("Not a BST");
    }
  }
}
 
// This code is contributed by lokeshmvs21.

Output

Is BST

Note: It is assumed that you have helper functions minValue() and maxValue() that return the min or max int value from a non-empty tree

Time Complexity: O(N2), As we visit every node just once and our helper method also takes O(N) time, so overall time complexity becomes O(N) * O(N) = O(N2)
Auxiliary Space: O(H), Where H is the height of the binary tree, and the extra space is used due to the function call stack.

Approach (Efficient):

The idea is to write a utility helper function isBSTUtil(struct node* node, int min, int max) that traverses down the tree keeping track of the narrowing min and max allowed values as it goes, looking at each node only once. The initial values for min and max should be INT_MIN and INT_MAX — they narrow from there. 

Note: This method is not applicable if there are duplicate elements with the value INT_MIN or INT_MAX.

Follow the below steps to solve the problem:

  • Call the isBstUtil function for the root node and set the minimum value as INT_MIN and the maximum value as INT_MAX
    • If the current node is NULL then return true
    • If the value of the node is less than the minimum value possible or greater than the maximum value possible then return false
    • Call the same function for the left and the right subtree and narrow down the minimum and maximum values for these calls accordingly

Below is the implementation of the above approach: 

C++




#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree node has data,
pointer to left child and
a pointer to right child */
class node {
public:
    int data;
    node* left;
    node* right;
 
    /* Constructor that allocates
    a new node with the given data
    and NULL left and right pointers. */
    node(int data)
    {
        this->data = data;
        this->left = NULL;
        this->right = NULL;
    }
};
 
int isBSTUtil(node* node, int min, int max);
 
/* Returns true if the given
tree is a binary search tree
(efficient version). */
int isBST(node* node)
{
    return (isBSTUtil(node, INT_MIN, INT_MAX));
}
 
/* Returns true if the given
tree is a BST and its values
are >= min and <= max. */
int isBSTUtil(node* node, int min, int max)
{
    /* an empty tree is BST */
    if (node == NULL)
        return 1;
 
    /* false if this node violates
    the min/max constraint */
    if (node->data < min || node->data > max)
        return 0;
 
    /* otherwise check the subtrees recursively,
    tightening the min or max constraint */
    return isBSTUtil(node->left, min, node->data - 1)
           && // Allow only distinct values
           isBSTUtil(node->right, node->data + 1,
                     max); // Allow only distinct values
}
 
/* Driver code*/
int main()
{
    node* root = new node(4);
    root->left = new node(2);
    root->right = new node(5);
    root->left->left = new node(1);
    root->left->right = new node(3);
 
      // Function call
    if (isBST(root))
        cout << "Is BST";
    else
        cout << "Not a BST";
 
    return 0;
}
 
// This code is contributed by rathbhupendra

C




#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
 
/* A binary tree node has data, pointer to left child
   and a pointer to right child */
struct node {
    int data;
    struct node* left;
    struct node* right;
};
 
int isBSTUtil(struct node* node, int min, int max);
 
/* Returns true if the given tree is a binary search tree
 (efficient version). */
int isBST(struct node* node)
{
    return (isBSTUtil(node, INT_MIN, INT_MAX));
}
 
/* Returns true if the given tree is a BST and its
   values are >= min and <= max. */
int isBSTUtil(struct node* node, int min, int max)
{
    /* an empty tree is BST */
    if (node == NULL)
        return 1;
 
    /* false if this node violates the min/max constraint */
    if (node->data < min || node->data > max)
        return 0;
 
    /* otherwise check the subtrees recursively,
     tightening the min or max constraint */
    return isBSTUtil(node->left, min, node->data - 1)
           && // Allow only distinct values
           isBSTUtil(node->right, node->data + 1,
                     max); // Allow only distinct values
}
 
/* Helper function that allocates a new node with the
   given data and NULL left and right pointers. */
struct node* newNode(int data)
{
    struct node* node
        = (struct node*)malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
 
    return (node);
}
 
/* Driver code*/
int main()
{
    struct node* root = newNode(4);
    root->left = newNode(2);
    root->right = newNode(5);
    root->left->left = newNode(1);
    root->left->right = newNode(3);
 
      // Function call
    if (isBST(root))
        printf("Is BST");
    else
        printf("Not a BST");
 
    getchar();
    return 0;
}

Java




// Java implementation to check if given Binary tree
// is a BST or not
 
/* Class containing left and right child of current
 node and key value*/
class Node {
    int data;
    Node left, right;
 
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
public class BinaryTree {
    // Root of the Binary Tree
    Node root;
 
    /* Can give min and max value according to your code or
    can write a function to find min and max value of tree.
  */
 
    /* Returns true if given search tree is binary
     search tree (efficient version) */
    boolean isBST()
    {
        return isBSTUtil(root, Integer.MIN_VALUE,
                         Integer.MAX_VALUE);
    }
 
    /* Returns true if the given tree is a BST and its
      values are >= min and <= max. */
    boolean isBSTUtil(Node node, int min, int max)
    {
        /* an empty tree is BST */
        if (node == null)
            return true;
 
        /* false if this node violates the min/max
         * constraints */
        if (node.data < min || node.data > max)
            return false;
 
        /* otherwise check the subtrees recursively
        tightening the min/max constraints */
        // Allow only distinct values
        return (
            isBSTUtil(node.left, min, node.data - 1)
            && isBSTUtil(node.right, node.data + 1, max));
    }
 
    /* Driver code */
    public static void main(String args[])
    {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(4);
        tree.root.left = new Node(2);
        tree.root.right = new Node(5);
        tree.root.left.left = new Node(1);
        tree.root.left.right = new Node(3);
 
          // Function call
        if (tree.isBST())
            System.out.println("Is BST");
        else
            System.out.println("Not a BST");
    }
}

Python3




# Python program to check if a binary tree is bst or not
 
INT_MAX = 4294967296
INT_MIN = -4294967296
 
# A binary tree node
 
 
class Node:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
 
# Returns true if the given tree is a binary search tree
# (efficient version)
def isBST(node):
    return (isBSTUtil(node, INT_MIN, INT_MAX))
 
# Returns true if the given tree is a BST and its values
# >= min and <= max
 
 
def isBSTUtil(node, mini, maxi):
 
    # An empty tree is BST
    if node is None:
        return True
 
    # False if this node violates min/max constraint
    if node.data < mini or node.data > maxi:
        return False
 
    # Otherwise check the subtrees recursively
    # tightening the min or max constraint
    return (isBSTUtil(node.left, mini, node.data - 1) and
            isBSTUtil(node.right, node.data+1, maxi))
 
 
# Driver code
if __name__ == "__main__":
  root = Node(4)
  root.left = Node(2)
  root.right = Node(5)
  root.left.left = Node(1)
  root.left.right = Node(3)
 
  # Function call
  if (isBST(root)):
      print("Is BST")
  else:
      print("Not a BST")
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

C#




using System;
 
// C# implementation to check if given Binary tree
// is a BST or not
 
/* Class containing left and right child of current
 node and key value*/
public class Node {
    public int data;
    public Node left, right;
 
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
public class BinaryTree {
    // Root of the Binary Tree
    public Node root;
 
    /* can give min and max value according to your code or
    can write a function to find min and max value of tree.
  */
 
    /* returns true if given search tree is binary
     search tree (efficient version) */
    public virtual bool BST
    {
        get
        {
            return isBSTUtil(root, int.MinValue,
                             int.MaxValue);
        }
    }
 
    /* Returns true if the given tree is a BST and its
      values are >= min and <= max. */
    public virtual bool isBSTUtil(Node node, int min,
                                  int max)
    {
        /* an empty tree is BST */
        if (node == null) {
            return true;
        }
 
        /* false if this node violates the min/max
         * constraints */
        if (node.data < min || node.data > max) {
            return false;
        }
 
        /* otherwise check the subtrees recursively
        tightening the min/max constraints */
        // Allow only distinct values
        return (
            isBSTUtil(node.left, min, node.data - 1)
            && isBSTUtil(node.right, node.data + 1, max));
    }
 
    /* Driver code */
    public static void Main(string[] args)
    {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(4);
        tree.root.left = new Node(2);
        tree.root.right = new Node(5);
        tree.root.left.left = new Node(1);
        tree.root.left.right = new Node(3);
       
        // Function call
        if (tree.BST) {
            Console.WriteLine("IS BST");
        }
        else {
            Console.WriteLine("Not a BST");
        }
    }
}
 
// This code is contributed by Shrikant13

Javascript




// Javascript implementation to
// check if given Binary tree
// is a BST or not
  
/* Class containing left and right child of current
 node and key value*/
 
class Node
{
    constructor(item)
    {
        this.data=item;
        this.left=this.right=null;
    }
}
 
 //Root of the Binary Tree
    let root;
     
    /* can give min and max value according to your code or
    can write a function to find min and max value of tree. */
  
    /* returns true if given search tree is binary
     search tree (efficient version) */
    function isBST()
    {
        return isBSTUtil(root, Number.MIN_VALUE,
                               Number.MAX_VALUE);
    }
     
    /* Returns true if the given tree is a BST and its
      values are >= min and <= max. */
    function isBSTUtil(node,min,max)
    {
        /* an empty tree is BST */
        if (node == null)
            return true;
  
        /* false if this node violates
        the min/max constraints */
        if (node.data < min || node.data > max)
            return false;
  
        /* otherwise check the subtrees recursively
        tightening the min/max constraints */
        // Allow only distinct values
        return (isBSTUtil(node.left, min, node.data-1) &&
                isBSTUtil(node.right, node.data+1, max));
    }
     
     /* Driver program to test above functions */
        root = new Node(4);
        root.left = new Node(2);
        root.right = new Node(5);
        root.left.left = new Node(1);
        root.left.right = new Node(3);
  
        if (isBST())
            document.write("IS BST<br>");
        else
            document.write("Not a BST<br>");
 
// This code is contributed by rag2127

Output

Is BST

Time Complexity: O(N), Where N is the number of nodes in the tree
Auxiliary Space: O(1), if Function Call Stack size is not considered, otherwise O(H) where H is the height of the tree

Check whether the binary tree is BST or not using inorder traversal:

The idea is to use Inorder traversal of a binary search tree generates output, sorted in ascending order. So generate inorder traversal of the  given binary tree and check if the values are sorted or not

Follow the below steps to solve the problem:

  • Do In-Order Traversal of the given tree and store the result in a temp array. 
  • This method assumes that there are no duplicate values in the tree
  • Check if the temp array is sorted in ascending order, if it is, then the tree is BST.

Note: We can avoid the use of an Auxiliary Array. While doing In-Order traversal, we can keep track of previously visited nodes. If the value of the currently visited node is less than the previous value, then the tree is not BST.

Below is the implementation of the above approach:

C++




// C++ program to check if a given tree is BST.
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree node has data, pointer to
left child and a pointer to right child */
struct Node {
    int data;
    struct Node *left, *right;
 
    Node(int data)
    {
        this->data = data;
        left = right = NULL;
    }
};
 
bool isBSTUtil(struct Node* root, Node*& prev)
{
    // traverse the tree in inorder fashion and
    // keep track of prev node
    if (root) {
        if (!isBSTUtil(root->left, prev))
            return false;
 
        // Allows only distinct valued nodes
        if (prev != NULL && root->data <= prev->data)
            return false;
 
        prev = root;
 
        return isBSTUtil(root->right, prev);
    }
 
    return true;
}
 
bool isBST(Node* root)
{
    Node* prev = NULL;
    return isBSTUtil(root, prev);
}
 
/* Driver code*/
int main()
{
    struct Node* root = new Node(3);
    root->left = new Node(2);
    root->right = new Node(5);
    root->left->left = new Node(1);
    root->left->right = new Node(4);
 
    // Function call
    if (isBST(root))
        cout << "Is BST";
    else
        cout << "Not a BST";
 
    return 0;
}

Java




// Java program to check if a given tree is BST.
import java.io.*;
 
class GFG {
    /* A binary tree node has data, pointer to
    left child and a pointer to right child */
    public static class Node {
        public int data;
        public Node left, right;
 
        public Node(int data)
        {
            this.data = data;
            left = right = null;
        }
    };
 
    static Node prev;
 
    static Boolean isBSTUtil(Node root)
    {
        // traverse the tree in inorder fashion and
        // keep track of prev node
        if (root != null) {
            if (!isBSTUtil(root.left))
                return false;
 
            // Allows only distinct valued nodes
            if (prev != null && root.data <= prev.data)
                return false;
 
            prev = root;
 
            return isBSTUtil(root.right);
        }
        return true;
    }
 
    static Boolean isBST(Node root)
    {
        return isBSTUtil(root);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        Node root = new Node(3);
        root.left = new Node(2);
        root.right = new Node(5);
        root.left.left = new Node(1);
        root.left.right = new Node(4);
 
        // Function call
        if (isBST(root))
            System.out.println("Is BST");
        else
            System.out.println("Not a BST");
    }
}
 
// This code is contributed by Shubham Singh

Python3




# Python3 program to check
# if a given tree is BST.
import math
 
# A binary tree node has data,
# pointer to left child and
# a pointer to right child
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
 
def isBSTUtil(root, prev):
 
    # traverse the tree in inorder fashion
    # and keep track of prev node
    if (root != None):
        if (isBSTUtil(root.left, prev) == True):
            return False
 
        # Allows only distinct valued nodes
        if (prev != None and
                root.data <= prev.data):
            return False
 
        prev = root
        return isBSTUtil(root.right, prev)
 
    return True
 
 
def isBST(root):
    prev = None
    return isBSTUtil(root, prev)
 
 
# Driver Code
if __name__ == '__main__':
    root = Node(3)
    root.left = Node(2)
    root.right = Node(5)
    root.right.left = Node(1)
    root.right.right = Node(4)
 
    # Function call
    if (isBST(root) == None):
        print("Is BST")
    else:
        print("Not a BST")
 
# This code is contributed by Srathore

C#




// C# program to check if a given tree is BST.
using System;
public class GFG {
    /* A binary tree node has data, pointer to
    left child and a pointer to right child */
    public class Node {
        public int data;
        public Node left, right;
 
        public Node(int data)
        {
            this.data = data;
            left = right = null;
        }
    };
 
    static Node prev;
 
    static Boolean isBSTUtil(Node root)
    {
        // traverse the tree in inorder fashion and
        // keep track of prev node
        if (root != null) {
            if (!isBSTUtil(root.left))
                return false;
 
            // Allows only distinct valued nodes
            if (prev != null && root.data <= prev.data)
                return false;
 
            prev = root;
 
            return isBSTUtil(root.right);
        }
        return true;
    }
 
    static Boolean isBST(Node root)
    {
        return isBSTUtil(root);
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        Node root = new Node(3);
        root.left = new Node(2);
        root.right = new Node(5);
        root.left.left = new Node(1);
        root.left.right = new Node(4);
 
        // Function call
        if (isBST(root))
            Console.WriteLine("Is BST");
        else
            Console.WriteLine("Not a BST");
    }
}
 
// This code is contributed by Rajput-Ji

Javascript




// Javascript program to check if a given tree is BST.   
    class Node
    {
        constructor(data)
        {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
     
    let prev;
  
    function isBSTUtil(root)
    {
     
        // traverse the tree in inorder fashion and
        // keep track of prev node
        if (root != null)
        {
            if (!isBSTUtil(root.left))
                return false;
 
            // Allows only distinct valued nodes
            if (prev != null && root.data <= prev.data)
                return false;
 
            prev = root;
 
            return isBSTUtil(root.right);
        }
        return true;
    }
 
    function isBST(root)
    {
        return isBSTUtil(root);
    }
     
    let root = new Node(3);
    root.left = new Node(2);
    root.right = new Node(5);
    root.left.left = new Node(1);
    root.left.right = new Node(4);
  
    if (isBST(root))
        document.write("Is BST");
    else
        document.write("Not a BST");
 
// This code is contributed by divyeshrabadiya07.

Output

Not a BST

Time Complexity: O(N), Where N is the number of nodes in the tree
Auxiliary Space: O(H), Here H is the height of the tree and the extra space is used due to the function call stack. 

Please write comments if you find any bug in the above programs/algorithms or other ways to solve the same problem.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!