Menu
CoddyTech

Validate Binary Search Tree

You get a binary tree stored in the array tree in level order. The root sits at index 0, the children of the node at index i sit at 2*i+1 (left) and 2*i+2 (right), -1 marks an empty spot, and the array may end with extra -1 entries.

Write a function named isValidBST that returns true if the tree is a binary search tree and false otherwise. In a binary search tree, every node's value is strictly greater than every value in its left subtree and strictly smaller than every value in its right subtree. Two equal values can never both be in a valid tree.

Function

isValidBST(tree: integer-array) → boolean
treeinteger-array
the binary tree in level order, with -1 for an empty spot
Returnsboolean
true if the tree is a binary search tree, false otherwise

Constraints

  • 1 ≤ tree.length ≤ 32767
  • Each tree[i] is -1 or a value with 0 ≤ tree[i] ≤ 105.
  • tree[0] is never -1, so the tree has at least one node.
  • The array may end with extra -1 entries past the last node.
  • Both children of an empty spot are empty too, and the depth is at most 14.
  • Values may repeat.

Examples

Input
tree = [8, 3, 12, 1, 6, 10, 15]
Output
true
Explanation
Each node sits on the correct side of every node above it. Read in order (left subtree, node, right subtree), the values come out as 1, 3, 6, 8, 10, 12, 15, strictly increasing, which is what a search tree gives.

lock icon+16 hidden tests on Submit

challenge icon

Follow-up

The parent of the node at index i sits at (i-1)/2, rounded down. Can you walk the tree in order with O(1) extra space, moving through parents instead of keeping a stack or recursing?

Reset code
def isValidBST(tree):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

tree = [8, 3, 12, 1, 6, 10, 15]

Expected

true