Problem · Tree
Validate Binary Search Tree
Learn this problemProblem statement
A binary tree is represented by aligned arrays. Node i has value values[i]; left[i] and right[i] contain child indices, or -1 when that child is absent. The index root identifies the root node.
Return true if the tree is a valid binary search tree and false otherwise.
For every node, every value in its left subtree must be strictly smaller and every value in its right subtree must be strictly greater. Therefore duplicate values make the tree invalid.
Function
isValidBST(values: int[], left: int[], right: int[], root: int) → booleanExamples
Example 1
values = [2,1,3]left = [1,-1,-1]right = [2,-1,-1]root = 0return = trueThe left value 1 is smaller than 2, and the right value 3 is greater.
Example 2
values = [5,1,4,3,6]left = [1,-1,3,-1,-1]right = [2,-1,4,-1,-1]root = 0return = falseNode value 4 lies in the right subtree of 5 but is not greater than 5.
Constraints
0 <= values.length <= 1000.left.length = right.length = values.length.- Node values are unique signed 32-bit integers.
- Child entries are
-1or valid node indices, and the arrays describe one finite binary tree. root = -1exactly when the tree is empty; otherwise it is a valid node index.