| Learn | Algorithm - Check if a tree is BST or not - Algorithm to check if a given binary tree is bst |
|---|
| Algorithm to check if a given binary tree is BST A binary tree is BST if it satisfies any one of the following condition:
So a straightforward recursive algorithm would be: The above recursive algorithm is correct but inefficient, because it traverses each node mutiple times. Another approach to minimize the multiple visits of each node is to remember the min and max possible values of the keys in the subtree we are visiting. Let the minimum possible value of any key be It will be initially called as: Another approach will be to do inorder traversal of the Binary tree. If the inorder traversal produces a sorted sequence of keys then the given tree is a BST. To check if the inorder sequence is sorted remember the value of previously visited node and compare it against the current node. |
Read Article
https://develop.horje.com/learn/1434/reference