Check if binary tree is bst in java

In this post, we will see check if binary tree is Binary search tree(BST) in java.


Algorithm

Here is simple algorithm to check if given Binary tree is Binary search tree(BST) or not.
You might think that you can just check current node is less than right child and more than the left child should work but it won’t.
You need to find a range of minimum and maximum, if any node does not lie between minimum and maximum then it won’t be binary search tree.

  • If root is null then return true
  • If root.data is not between minimum and maximum return false
  • Traverse left child of root and update maximum value with currentNode
  • Traverse right child of root and update minimum value with currentNode
  • If both left child and right child return true else return false.

Complete java program to check if Binary tree is BST

Output

Is current binary is BST: true

That’s all about how to Check if binary tree is bst in java.

Leave a Reply

Your email address will not be published. Required fields are marked *