Validate Binary Search Tree

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

A valid BST is defined as follows:

  • The left subtree of a node contains only nodes with keys strictly less than the node's key.
  • The right subtree of a node contains only nodes with keys strictly greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.
Example 1
        2
       / \
      1   3
Inputroot = [2,1,3]
Outputtrue
The root value 2 is greater than its left child 1 and less than its right child 3, so the tree is a valid BST.
Example 2
        5
       / \
      1   4
         / \
        3   6
Inputroot = [5,1,4,null,null,3,6]
Outputfalse
The node with value 3 is in the right subtree of 5, but it is less than 5, so the tree is not a valid BST.

Constraints

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

Asked at 19 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate