Validate Binary Search Tree | Binary Tree is BST or Not

In this post, I am going to discuss a very famous interview problem validate binary search tree or in other words check if a binary tree is BST or not.

Given the root of a binary tree, We have to write a code to check if it is a binary search tree (BST) or not.

The property of a valid binary search tree (BST) is:

i) The left subtree of a node contains only nodes with keys less than the node’s key.
ii) The right subtree of a node contains only nodes with keys greater than the node’s key.
iii) Both the left and right subtrees must also be binary search trees.

For example –

check if a binary tree is BST or not

We have given four binary trees, out of which first and third are binary search tree.

Programming video tutorials

Binary tree zigzag level order traversal

We have discussed the problem statement. Now, let’s discuss how we can approach this problem.

In this problem, we have given a binary tree and to validate whether it’s a BST or not we have to traverse this tree. So, which tree traversal algorithm should we use to traverse a binary tree?

binary tree traversal technique
Binary tree traversal technique

Validate binary search tree – video tutorial

Validate Binary Search Tree – Java Code

In this example, I am going to use inorder traversal to solve this problem. Why i am using inorder traversal? When we do the inorder traversal of a binary search tree we get the result sorted in ascending order.

If the result are sorted in ascending order, It means the given binary tree is a binary search tree.

The time complexity of this approach is O(n) and it’s space complexity is O(n).

validate binary search tree

Programming questions on binary tree

Check If a Binary Tree is BST or Not – Java Code

Let’s improve our previous solution. Let’s think in this way, to satisfy the property of a binary search tree each node value should be in certain range.

Using this trick we traverses down the tree keeping track of the narrowing start and end range as it goes, looking at each node only once. The initial values for start and end range should be null.

The time complexity of this approach is O(n) and it’s space complexity is O(1).

Validate binary search tree – video tutorial

Tagged , . Bookmark the permalink.
blank

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.