Practice · Trees · 8 of 12

Check a Binary Search Tree

You are given root, the root of a non-empty binary tree.

Return true if it is a valid binary search tree, and false otherwise. In a valid binary search tree, for every node:

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

So no value may appear twice, and the rule covers whole subtrees, not only a node's children.

Trees are written in level order, row by row from the top, with null where a node is missing: [4, 2, 7, null, 3] is 4 at the root, 2 and 7 below it, and 3 as the right child of 2.

Example 1

Input
root = [8, 4, 12, 2, 6, 10, 14]
Output
true

Example 2

Input
root = [8, 4, 12, 2, 6, 7, 14]
Output
false
7 is a fine left child for 12, but it is in 8's right subtree, so it must be larger than 8.

Constraints

  • The tree holds 1 to 1000 nodes.
  • Every value is between −2³¹ and 2³¹ − 1.