InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Validate Binary Search Tree

medium Original ↗ 00:00

Problem

You are given the root of a binary tree. Decide whether it is a valid binary search tree (BST).

A tree is a valid BST when every node satisfies all of the following:

  • Every value in the node’s left subtree is strictly less than the node’s value.
  • Every value in the node’s right subtree is strictly greater than the node’s value.
  • Both the left and right subtrees are themselves valid BSTs.

The comparison is strict, so duplicate values are never allowed. Note that the rule applies to the entire subtree, not just the immediate children — a node deep on the left must still be smaller than every ancestor it sits under on the left side.

Return True if the tree is a valid BST and False otherwise.

Examples

  • Input: root = [2, 1, 3] → Output: True Left child 1 < 2, right child 3 > 2.
  • Input: root = [5, 1, 4, null, null, 3, 6] → Output: False Root is 5; its right child 4 is not greater than 5, so the tree is invalid.
  • Input: root = [5, 4, 6, null, null, 3, 7] → Output: False 3 is a left-descendant of 6 (so 3 < 6 holds locally) but 3 < 5 must also hold since 3 lives in the right subtree of the root — it does not, so the tree is invalid.

Constraints

  • The number of nodes is in [1, 10^4].
  • -2^31 <= Node.val <= 2^31 - 1 (values can hit the 32-bit integer extremes, so sentinel bounds must handle them).

Think about it first

Hint 1 Checking only "left child < node < right child" at each node is not enough. A grandchild can satisfy its parent's rule yet violate an ancestor's. What information does a node need from *above* it?
Hint 2 As you descend, every node is confined to an open interval `(low, high)`. Going left tightens the upper bound to the current value; going right tightens the lower bound. Pass those bounds down.
Hint 3 Alternatively, remember what an **inorder** traversal of a BST produces: a strictly increasing sequence. Walk inorder and verify each value is larger than the one before it.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug