Check if a binary tree is binary search tree or not in java


If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

In this post, we will see how to check if given binary tree is binary search tree or not. This is one of important interview questions on binary tree.
We will see two approaches to check if binary tree is bst or not.

First method:

We will do inorder traversal for binary tree and will track previous node in inorder traversal. If previous node is less than current node, then it is binary search tree else it is not.

Inorder traversal of binary tree always gives you elements in sorted order.

Java program:

Second Method:

We will use min max range for a node. If is greater than min and less than max then it follows binary search tree property.

  • When you traverse left, current node should be greater than min.
  • When you traverse right, current node should be less than max.
  • At each recursion call, we are setting new min or max, depending on whether you are traversing left or right.

Java program:

Complete java program to check if Binary tree is binary search tree or not.

When you run above code, you will get below output:


Add Comment