Problem · Tree
Validate Binary Search Tree
Learn this problemProblem statement
Given the root of a binary tree, return true if it is a valid binary search tree and false otherwise.
For every node, every value in its left subtree must be strictly smaller than the node's value, every value in its right subtree must be strictly greater, and both subtrees must satisfy the same rules. Duplicate values therefore make the tree invalid.
Tree inputs use level-order JSON notation with null for a missing child.
Function
validateBST(root: TreeNode) → booleanExamples
Example 1
root = [4,2,5,1,3]return = trueEvery value under node 2 lies between 1 and 3; the entire left subtree is below 4, and node 5 is above 4.
Example 2
root = [5,1,7,null,null,4,8]return = falseNode 4 is in the right subtree of 5, so it violates the lower bound imposed by the root.
Constraints
1 <= number of nodes <= 5000-10^6 <= node.val <= 10^6