Validate Binary Search Tree

Medium Trees AI round

root is the root of a binary tree, which may be empty.

The tree is a binary search tree when every node holds a value that is larger than every value in its left subtree and smaller than every value in its right subtree. Each node is held to this on its own, so a value that suits its parent can still break the rule for a node further up. Equal values break it too, so a binary search tree never holds the same value twice.

Return true when the tree is a binary search tree and false when it is not. An empty tree, and a tree of one node, are binary search trees.

Example 1

Input: root = [8,3,10,1,6,null,14]
Output: true
83101614

Example 2

Input: root = [10,5,15,null,null,9,20]
Output: false
10515920

9 sits under 15, on the right of 10, yet it is smaller than 10: every node suits its parent, but 9 breaks the rule for the root.

Example 3

Input: root = [7,3,9,3]
Output: false
7393

Constraints

  • 0 ≤ number of nodes ≤ 10⁵
  • -2³¹ ≤ node.val ≤ 2³¹ − 1

Watch the explanation

More Trees

All Trees problems