Do you want to know how to validate binary search tree? If yes, then check out this blog to understand the best ways to validate binary search tree

Every programmer understands how important Data Structures and Algorithms are for them. But some DSA concepts can be outrageously complex to understand, Trees being a classic example for that.

They are one of the most foundational concepts for advanced Data Structures and Algorithms like Graphs, Breadth-First Search and Depth-First-Search etc.

In this blog, we will learn about how to validate binary search tree. But first, letâ€™s understand what is a binary search tree.

## What is a Binary Search Tree (or BST) ?

A binary tree is a data structure made of nodes connected to each other, which can be represented as a tree (note that no actual tree shape forms in the memory.

It is just to understand the working of tree in a better manner) with at most two nodes connected to a single node (which constitute the left subtree and right subtree respectively).

A binary tree data structure has the following components for each node:

**Key :**The data value of the node**Left:**A reference to the left child node**Right:**A reference to the right child node

A Binary Search Tree is a special type of binary tree in which satisfies the following conditions :

- The left sub-tree must contain all keys which are less than the current nodeâ€™s key value
- The right sub-tree must contain all keys which are greater than the current nodeâ€™s key value
- No key value should be repeated in the entire BST
- Both the left sub-tree

## What do we mean by Validating a BST ?

The problem that we are dealing with here is to tell whether a given binary tree is BST or not.

If the given tree is a BST then we need to return true, otherwise we should return false.

In order to do that, we need to check the conditions of the Binary Search Tree, discussed earlier in this article, for the given tree.

There are several methods to validate the given tree. Let us discuss them one by one.

## Validate Binary Search Tree

### Brute Force Approach

The brute force approach (in general) is an approach aimed at just solving the problem and getting the desired results. It does not cater to the scope for optimization and therefore, not a preferred approach for practical purposes.

- Check if the root has no children. If yes, return true
- Traverse the left sub-tree. If for any node, the value of the node is greater than the root, return false.
- Traverse the right sub-tree. If for any node, the value of the node is less than the root, return false.
- Repeat the above steps for each node in the left and right sub-tree respectively.

**Time Complexity : **O(n^{2})

**Auxiliary Space Used:** O(lg(n))

### Using Upper and Lower Limit Values

In this method three variable, the currentNode, upperLimit, lowerLimit are declared as:

- currentNode = root
- upperLimit = NULL
- lowerLimit = NULL

Then we follow the following steps:

- If the currentNode = null, return true
- If lowerLimit is not null and currentNode <= lowerLimit , return false
- If upperLimit is not null and currentNode >= upperLimit , return false
- Repeat the above steps for the left sub-tree and check whether it is a BST or not having
**currentNode as upperLimit**and**lowerLimit as lowerLimit**. If the left sub-tree is not a BST, return false - Keep checking that the right sub-tree is BST or not having the
**currentNode as lowerLimit**and**upperLimit as upperLimit**. - If the right sub-tree is not a BST, return false, else return true

**Time Complexity : **O(n)

**Auxiliary Space Used:** O(1)

### Using In-order Traversal

This method uses in-order traversal of the tree. It works because the level order search results of a BST result in a sorted order of the tree elements.

When we are performing the in-order traversal, the control first goes to the left subtree, then the current node, and then the right subtree.

If we perform this in a Binary Search Tree, we know that the three elements must be in an increasing order, because any value in the left subtree will be smaller than the current node and any value in the right subtree will be greater than the current node.

Thus, we only need to perform in-order traversal on the given tree and check if the previous element in the traversal is less than the current element. If not, we return false. If false is not returned for the entire traversal, we return true.

**Time Complexity : **O(n)

**Auxiliary Space Used:** O(lg(n))

## You May Also Like

9+ Java Swing Vs JavaFX Comparisons â€” Which Is Better?

## Code Implementation

Now, we will discuss how to implement the above logic into both C++ and Java. For this, we will be using the following tree as input.

### Java Implementation

```
import java.io.*;
class solution {
static class node {
Â Â int val;
Â Â node left, right;
}
static node newNode(int info)
{
Â Â node Node = new node();
Â Â Node.val = info;
Â Â Node.left = Node.right = null;
Â Â return Node;
}
static int maxVal(node Node)
{
Â Â if (Node == null) {
Â Â return Integer.MIN_VALUE;
Â Â }
Â Â int value = Node.val;
Â Â int leftMax = maxVal(Node.left);
Â Â int rightMax = maxVal(Node.right);
Â Â return Math.max(value, Math.max(leftMax, rightMax));
}
static int minVal(node Node)
{
Â Â if (Node == null) {
Â Â return Integer.MAX_VALUE;
Â Â }
Â Â int value = Node.val;
Â Â int leftMax = minVal(Node.left);
Â Â int rightMax = minVal(Node.right);
Â Â return Math.min(value, Math.min(leftMax, rightMax));
}
static int validateBST(node Node)
{
Â Â if (Node == null) {
Â Â return 1;
Â Â }
Â Â if (Node.left != null
Â Â Â Â && maxVal(Node.left) > Node.val) {
Â Â return 0;
Â Â }
Â Â if (Node.right != null
Â Â Â Â && minVal(Node.right) < Node.val) {
Â Â return 0;
Â Â }
Â Â if (validateBST(Node.left) != 1
Â Â Â Â || validateBST(Node.right) != 1) {
Â Â return 0;
Â Â }
Â Â return 1;
}
public static void main(String[] args)
{
Â Â node root = newNode(10);
Â Â root.left = newNode(7);
Â Â root.right = newNode(13);
Â Â root.left.left = newNode(5);
Â Â root.left.right = newNode(9);
Â Â root.right.left = newNode(11);
Â Â root.right.right = newNode(15);
Â Â if (validateBST(root) == 1) {
Â Â System.out.print("Given tree is a BST");
Â Â }
Â Â else {
Â Â System.out.print("Given tree is not a BST");
Â Â }
}
}
```

**Output:**

Given tree is a BST

### C++ Implementation

This is the implementation of the above method in C++ to check if the given tree is a BST or not.

```
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
int maxValue(struct node* node)
{
if (node == NULL) {
return INT16_MIN;
}
int value = node->data;
int leftMax = maxValue(node->left);
int rightMax = maxValue(node->right);
return max(value, max(leftMax, rightMax));
}
int minValue(struct node* node)
{
if (node == NULL) {
return INT16_MAX;
}
int value = node->data;
int leftMax = minValue(node->left);
int rightMax = minValue(node->right);
return min(value, min(leftMax, rightMax));
}
int isBST(struct node* node)
{
if (node == NULL)
return 1;
if (node->left != NULL
&& maxValue(node->left) > node->data)
return 0;
if (node->right != NULL
&& minValue(node->right) < node->data)
return 0;
if (!isBST(node->left) || !isBST(node->right))
return 0;
return 1;
}
int main()
{
struct node* root = newNode(4);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(1);
root->left->right = newNode(3);
if (isBST(root))
printf("Is BST");
else
printf("Not a BST");
return 0;
}
```

**Output:**

Given tree is a BST

## Conclusion

In this article, we discussed about how to validate binary search tree. We also discussed various ways in which we can check if a binary tree is a BST or not and also how to implement those logics in C++ and Java.

From the above mentioned methods, the in-order traversal method is the most practically used (and preferred ) method for BST validation although other methods may also work according to the nature of the program. If you think we have missed anything about validate binary search tree then comment down below.