Validate Binary Search Tree

35 min · isValidBST()

A tree can look ordered one parent at a time and still hide a bad value three levels down. Your check has to protect the whole family tree, not just each immediate pair.

A binary search tree (BST) is a binary tree where every node obeys two strict rules:

  • every value anywhere in its left subtree is smaller than the node's value, and
  • every value anywhere in its right subtree is larger than the node's value.

Given root, return true when the entire tree follows those rules. Return false otherwise.

A few ground rules:

  • The ordering is strict, so a duplicate value makes the tree invalid.
  • An empty tree and a one-node tree are valid.
  • The input arrives as a tree; examples display it as a level-order array where null marks a missing child.

Constraints

  • 0 <= node count <= 10_000
  • -2_147_483_648 <= node.val <= 2_147_483_647

Hints

Local checks aren't enough

A node in the root's left subtree must be smaller than the root even when it isn't the root's child. What information could you carry down the tree to enforce that?

Give every node a legal interval

The root starts with no lower or upper limit. Moving left tightens the upper limit to the current value; moving right tightens the lower limit.

Keep the interval open

Reject a value that is equal to either limit. Open bounds encode the strict rule and catch duplicates without a special case.

Follow-up

Could you validate the tree while reading its values in sorted order, without carrying explicit lower and upper bounds?

Visible cases

Examples

Example 1

ready
Input
root = [
  2,
  1,
  3
]
Expected
true
Why
1 < 2 < 3, so every subtree stays inside its bounds

Example 2

ready
Input
root = [
  5,
  1,
  4,
  null,
  null,
  3,
  6
]
Expected
false
Why
3 sits in 5's right subtree but is smaller than 5

Example 3

ready
Input
root = [
  2,
  2,
  2
]
Expected
false
Why
BST ordering is strict, so equal children fail

Interview signal

Asked at

AmazonMetaMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite