InterviewPrepKit

Home / Coding / Trees

Validate Binary Search Tree

medium Original ↗
Solving tips
  • Key trap: checking only left-child < node < right-child is wrong; a deep node must respect every ancestor's bound.
  • Thread an allowed open interval (low, high) down the recursion: going left tightens high to node.val, going right tightens low; O(n) time, O(h) space.
  • Alternative: an inorder traversal of a valid BST is strictly increasing, so walk inorder tracking the previous value.
  • Use strict comparisons (duplicates are invalid) and float('-inf')/float('inf') sentinels since node values can hit the 32-bit extremes.

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. All good.
  • 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 BST rule breaks immediately.
  • 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.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.