Validate Binary Search Tree

Shaila Nasrin
6 min readApr 14, 2021

The problem states that we will be given a binary tree and we have to determine if it is a valid binary search tree(BST) or not. you can find this problem in Leetcode and in Hackerrank.

First of all, what is a binary tree?

A binary tree is a tree that has at most two child nodes.

Then what is a binary search tree?

A binary search tree(BST) is a kind of binary tree where each node is greater than its left node and smaller than its right node.

If you do not know how to implement a binary search tree you read my post about it.

Example of a binary search tree(BST)

In the above picture, we have a valid binary search tree(BST). In order to validate a BST, we have to check if the current node is greater than the left node and smaller than the right node. If the whole tree abides by this rule then it is a valid BST, otherwise, it is not.

Code:

How does the code work?

As we will be comparing each node with its left and right node, initially we don’t know the right and left node…

--

--