# Solution: Validate Binary Search Tree

Let's solve the Validate Binary Search Tree problem using the Tree Depth-First Search pattern.

We'll cover the following

## Statement

Given the root of a binary tree, check whether it is a valid binary search tree (BST).

A binary tree is a valid BST if for every node:

• The left subtree of a node contains only nodes with keys less than the nodeâ€™s key.

• The right subtree of a node contains only nodes with keys greater than the nodeâ€™s key.

• Both the left and right subtrees are valid BSTs.

Constraints:

• $-10^{4} \leq$ Node.data $\leq 10^{4}$

• The tree contains nodes in the range $[1, 500]$.

## Solution

For this solution, we will recursively perform the inorder (left subtree, root, right subtree) traversal on the binary tree. We will be using inorder traversal to get elements in sorted order. We will also use a prev variable to hold the value of the previous node visited during the inorder traversal.

We initialize the prev variable with negative infinity. Then, we perform the inorder traversal on the tree and check whether the current nodeâ€™s value is less than the prev value. If it is, return FALSE since it is not a valid BST. If not, update the value of prev with the current nodeâ€™s value, and continue the traversal. If all nodes have been traversed and no nodeâ€™s value was less than the prev value, it means that the tree is a valid BST. Therefore, we return TRUE.

Letâ€™s look at an example below:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.