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

Last updated on June 4th, 2017 at 12:26 am

Previous
Next

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 node.data 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:

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog