Solution: Validate Binary Search Tree

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

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:

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

  • The tree contains nodes in the range [1,500][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 80+ hands-on prep courses.