Skip to content
Problem 98 · LeetCode 98(opens in a new tab)

Validate Binary Search Tree

MediumBinary search trees

You are given the root of a binary tree. Decide whether it is a binary search tree: for every node, all the values anywhere in its left subtree are strictly smaller than the node's value, and all the values anywhere in its right subtree are strictly bigger.

Return true if the tree follows that rule at every node, and false otherwise. Equal values are not allowed on either side.

Example 1

Input:  root = [8, 4, 12, 2, 9]
Output: false
Why:    9 is in the left subtree of 8 but bigger than 8
2 more examples and the constraints

Example 2

Input:  root = [5, 3, 7]
Output: true
Why:    3 < 5 < 7

Example 3

Input:  root = [4, 4]
Output: false
Why:    equal values break the rule

Constraints

  • 1 ≤ number of nodes ≤ 10,000
  • −2³¹ ≤ node value ≤ 2³¹ − 1

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Check each node against its subtreesO(n²)
  2. Pass the allowed range downO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a chain of 10,000 nodesVerdict
Check each node against its subtreesO(n²)
Mention it, then move on
Pass the allowed range downO(n)
Best; each node once

n = number of nodes, h = height of the tree.

Edge cases to test

  • A grandchild breaks the rule. Example 1: 9 is fine next to its parent 4 but is too big for the root 8.
  • Equal values. [4, 4] and [5, null, 5] are both false: the rule is strict.
  • Values at the 32-bit limits. [−2³¹, null, 2³¹ − 1] is valid. Starting the range at those values would wrongly reject it.
  • A single node. Always valid, whatever its value.

Common mistakes

  • Comparing each node only with its two children.
  • Allowing equal values with <= or >=.
  • Using the 32-bit minimum and maximum as the starting limits, so a node holding one of them fails.

How to talk through it

  1. 1Clarify. Are duplicates allowed? What range can values take?
  2. 2Show the trap. Draw a tree where every parent and child look fine but a grandchild breaks the rule.
  3. 3Give the brute force. Check each node against its whole subtrees; say it is O(n²) on a chain.
  4. 4Pass ranges down. Each call gets (lo, hi); going left lowers hi, going right raises lo. Code it with wide limits.
  5. 5Test out loud. Run the grandchild trap, an equal pair and a tree holding the 32-bit limits.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?