Validate a Binary Search Tree
Problem statement
Given the root of a binary tree, return whether it is a valid binary search tree.
For this practice, every node in a left subtree must have a value strictly less than its ancestor, and every node in a right subtree must have a value strictly greater than its ancestor. This rule applies to every ancestor, not only to each node’s immediate children. Duplicate values make the tree invalid. An empty tree is valid.
Input examples use level-order array notation with null for missing children.
Function
isValidBST(root: TreeNode) → booleanExamples
Example 1
root = [2,1,3]return = trueThe left value is smaller than 2 and the right value is greater.
Example 2
root = [5,1,4,null,null,3,6]return = falseValue 3 lies in the root’s right subtree but is less than 5.
Example 3
root = [2,2,3]return = falseA duplicate value in the left child violates strict BST ordering.
Constraints
- The tree contains
0to100nodes. -10^9 <= node.val <= 10^9.- Use strict inequalities for every subtree bound.