Implement the validateBinarySearchTree method that checks whether the given tree satisfies binary search tree rules.

The input contains a binary tree represented as an integer array tree in level-order format.

Your task is to check whether the tree is a valid binary search tree. In a valid BST, every value in the left subtree must be smaller than the current node, and every value in the right subtree must be greater than the current node.

The rule must be true for every node, not only for the root node.

Example 1

Input
tree (int[]) = [2,1,3]
size (int) = 3
Returns (boolean) true

Example 2

Input
tree (int[]) = [5,1,4,0,0,3,6]
size (int) = 7
Returns (boolean) false

Example 3

Input
tree (int[]) = [1,1]
size (int) = 2
Returns (boolean) false

Use minimum and maximum allowed boundaries while checking each node.

For the root, there is no boundary. When moving to the left child, the current node value becomes the maximum allowed value. When moving to the right child, the current node value becomes the minimum allowed value.

If any node is not strictly inside its allowed range, return false. If all nodes satisfy the rule, return true.

Pseudocode:

function validateBinarySearchTree(tree, size):
    return isValid(0, negativeInfinity, positiveInfinity)
function isValid(index, minValue, maxValue):
    if index >= size or tree[index] is missing:
        return true
    value = tree[index]
    if value <= minValue or value >= maxValue:
        return false
    leftValid = isValid(2 * index + 1, minValue, value)
    rightValid = isValid(2 * index + 2, value, maxValue)
    return leftValid and rightValid
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.