Binary Search Tree Validator

HardTree + Constraints

Description

Given the root of a binary tree, determine if it is a valid **binary search tree (BST)**. A valid BST is defined as: the left subtree of a node contains only nodes with keys **strictly less than** the node's key; the right subtree contains only nodes with keys **strictly greater than** the node's key; both subtrees must also be binary search trees. Tree nodes: `{ val, left, right }`.

Examples

Input: root = {val:2, left:{val:1,left:null,right:null}, right:{val:3,left:null,right:null}}

Output: true

Input: root = {val:5, left:{val:1,left:null,right:null}, right:{val:4,left:{val:3,left:null,right:null},right:{val:6,left:null,right:null}}}

Output: false

Node 4's right subtree contains 3, which is less than 5.

Constraints

  • •Number of nodes: 1 to 10⁴
  • •-2³¹ ≤ Node.val ≤ 2³¹ − 1

Your Solution

JavaScript·4 test cases·Max 5,000 chars · 2s timeout · 10 runs/30s
Loading...