Skip to content
Decoder

Validate a Binary Search Tree

Medium

Problem

Given the root of a binary tree, return whether it is a valid binary search tree (BST). In a valid BST, for every node:

- every value in its left subtree is strictly less than the node's value, and - every value in its right subtree is strictly greater.

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.

Example 1

Input
[2, 1, 3]
Output
True

Example 2

Input
[5, 1, 4, null, null, 3, 6]
Output
False
Why
4 is in 5's right subtree but is smaller

Example 3

Input
[5, 4, 6, null, null, 3, 7]
Output
False
Why
3 is below 6, which is fine, but it is also in 5's right subtree

An empty tree counts as valid.

Constraints

  • 0 <= number of nodes <= 10^4
  • -2^31 <= Node.val <= 2^31 - 1

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.