Search⌘ K
AI Features

Validate Binary Search Tree

Understand how to validate binary search trees by ensuring left nodes are less and right nodes are greater than the parent. This lesson guides you through using depth-first search and implementing constraints to confirm a correct BST structure.

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].

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Valid Binary Search Tree

1.

Is the following binary tree a valid binary search tree?

  9
 / \
2  10
   / \
  7  20
A.

True

B.

False


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

Try it yourself

Implement your solution in the following coding playground.

C++
usercode > main.cpp
// Definition for a binary tree node
// template<class T>
// class TreeNode {
// public:
// T data;
// TreeNode<T>* left;
// TreeNode<T>* right;
// TreeNode(const T data) : data(data), left(nullptr), right(nullptr) {}
// };
int ValidateBst(TreeNode<int>* root)
{
// Replace this placeholder return statement with your code
return false;
}
Validate Binary Search Tree