Validate Binary Search Tree

MediumTrees

Given the root of a binary tree, return true if it is a valid binary search tree, and false otherwise.

In a valid one, for every node, all the values in its left subtree are smaller than the node’s value and all the values in its right subtree are larger. Equal values are not allowed on either side.

On this page a tree is written in level order, top to bottom and left to right, with null where a child is missing: [6, 3, 8, 1] is 6 with children 3 and 8, and 3 with a left child 1.

Examples

Example 1
Input:  root = [10, 5, 15, 2, 7, 12, 20]
Output: true

Everything left of 10 is smaller, everything right of it is larger, and the same holds at 5 and at 15.

Example 2
Input:  root = [10, 5, 15, null, null, 8, 20]
Output: false

8 is a fine left child for 15, but it sits in the right subtree of 10 and is smaller than 10.

Constraints

  • The tree has 1 to 10⁴ nodes.
  • -2³¹ ≤ node.val ≤ 2³¹ - 1

Stuck?

Hint 1

Comparing each node with its own two children is not enough: a value deep in the left subtree must be smaller than the root too, not just smaller than its parent.

Hint 2

Pass a range down as you recurse: each node must lie strictly between a lower and an upper bound. Going left, the node’s value becomes the upper bound; going right, it becomes the lower one. An in-order walk that must keep rising works as well.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 12 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur