Implement binarySearchTreeValidate(root) — return true if the binary tree rooted at root is a valid binary search tree (BST), and false otherwise. A BST is a tree where every node's value is greater than every value in its left subtree and less than every value in its right subtree. That whole-subtree ordering is what lets you find, insert, and delete a value in O(height) time instead of scanning every node — it's the invariant behind ordered maps and sets in many standard libraries.
// A tree node:
// { val: number, left: Node | null, right: Node | null }
// root: Node | null — the root of the tree, or null for an empty tree.
// returns: boolean — true if the tree is a valid BST, false otherwise.
function binarySearchTreeValidate(root): boolean;
A leaf is a node whose left and right are both null. An empty tree is root === null.
// A valid BST: every left descendant < its ancestor < every right descendant.
// 5
// / \
// 3 8
// / \
// 1 4
const valid = {
val: 5,
left: { val: 3, left: { val: 1, left: null, right: null },
right: { val: 4, left: null, right: null } },
right: { val: 8, left: null, right: null },
};
binarySearchTreeValidate(valid); // → true
// NOT a BST, even though each node looks fine next to its own children.
// 5
// \
// 7
// /
// 4 ← 4 sits in 5's RIGHT subtree, but 4 < 5
const sneaky = {
val: 5,
left: null,
right: { val: 7, left: { val: 4, left: null, right: null }, right: null },
};
binarySearchTreeValidate(sneaky); // → false
In the second tree, 7 > 5 (good as 5's right child) and 4 < 7 (good as 7's left child). Every parent–child pair is locally ordered. But 4 lives somewhere in 5's right subtree, and the BST rule says everything there must exceed 5. It doesn't. So the tree is invalid — a fact you cannot see by only comparing a node to its immediate children.
{ val: 5, left: { val: 5, ... } }) makes the tree invalid here. (Some definitions allow duplicates on one side — we don't; treat equal values as a violation.)binarySearchTreeValidate(null) returns true.true.NaN, non-numeric values, cycles, or parent pointers — the input is always a finite binary tree of numbers.