AlgoFrames

Validate a BST

Standard · Write code · about 12 min

Given the root of a binary tree, return true if it is a valid binary search tree. Every key in the left subtree of a node must be smaller than the node key, and every key in the right subtree must be bigger. Equal keys are not allowed. An empty tree is valid.

Example 1

Input:

[[2,1,3]]

Output:

true

1 < 2 < 3.

Example 2

Input:

[[5,1,4,null,null,3,6]]

Output:

false

4 is right of 5 but smaller than 5.

Constraints

  • 0 ≤ number of nodes ≤ 1,000
  • -1,000 ≤ key ≤ 1,000
  • The tree is given in level order; null marks a missing child

Learn the idea first: Validating a BST and the in-order property, a visual lesson.

More Validating a BST and the in-order property problems