Menu
CoddyTech

Validate Binary Search Tree

A binary tree is stored in the array tree in heap order: the root is at index 0, the children of index i are 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 isValidBST, which 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.

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
Read in order (left subtree, node, right subtree), the values are 1, 3, 6, 8, 10, 12, 15. They strictly increase, so every node sits on the correct side of every ancestor.
challenge icon

Follow-up

A node's parent is at index (i-1)/2, rounded down. Can you walk the tree in order with O(1) extra space, moving through parents instead of a stack or recursion?

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

Test #1

Test #2

Test #3

Argument

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

Expected Output

true