98. Validate Binary Search Tree

time: O(n)

space: O(h), worst O(n)

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isValidBST = function(root) {
    return validate(root);
};

function validate(node, min = -Infinity, max = Infinity) {

    if (node === null) return true;

    const val = node.val;
    const isOutRange = !(min < val && val < max);
    if (isOutRange) return false;

    const left = validate(node.left, min, val);
    const right = validate(node.right, val, max);

    return left && right;
}

Last updated