class TreeNode { val: number; left: TreeNode | null; right: TreeNode | null; constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { this.val = val === undefined ? 0 : val; this.left = left === undefined ? null : left; this.right = right === undefined ? null : right; } } function isValidBST(root: TreeNode | null, min: number = -Infinity, max: number = Infinity): boolean { if (root === null) return true; if (root.val <= min || root.val >= max) return false; return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max); } // Tree structure: // 5 // / \ // 3 7 // / \ \ // 2 4 8 const tree = new TreeNode(5, new TreeNode(3, new TreeNode(2), new TreeNode(4)), new TreeNode(7, null, new TreeNode(8)) ); console.log(isValidBST(tree));
The function checks recursively if each node's value is within the allowed min and max range. The given tree satisfies BST properties, so the output is true.
// Tree structure: // 5 // / \ // 3 7 // / \ \ // 2 6 8 const invalidTree = new TreeNode(5, new TreeNode(3, new TreeNode(2), new TreeNode(6)), new TreeNode(7, null, new TreeNode(8)) ); console.log(isValidBST(invalidTree));
The node with value 6 is in the left subtree of 5 but is greater than 5, violating BST rules. So the function returns false.
function isValidBST(root: TreeNode | null): boolean {
if (!root) return true;
if (root.left && root.left.val >= root.val) return false;
if (root.right && root.right.val <= root.val) return false;
return isValidBST(root.left) && isValidBST(root.right);
}
// Tree:
// 10
// / \
// 5 15
// / \
// 6 20
const tree = new TreeNode(10,
new TreeNode(5),
new TreeNode(15, new TreeNode(6), new TreeNode(20))
);
console.log(isValidBST(tree));The function only checks immediate children values, missing deeper violations. The node with value 6 is in the right subtree of 10 but less than 10, so the tree is not a BST. The function returns true.
The min and max parameters define the valid range for each node's value based on its ancestors, ensuring the entire subtree respects BST rules, not just immediate children.
function countBSTSubtrees(root: TreeNode | null): number {
if (!root) return 0;
let count = 0;
if (isValidBST(root)) count++;
count += countBSTSubtrees(root.left);
count += countBSTSubtrees(root.right);
return count;
}
// Tree:
// 10
// / \
// 5 15
// / \
// 6 20
const tree = new TreeNode(10,
new TreeNode(5),
new TreeNode(15, new TreeNode(6), new TreeNode(20))
);
console.log(countBSTSubtrees(tree));The valid BST subtrees are rooted at 5, 15 (6 < 15 < 20), 6, and 20. The whole tree is invalid. Total valid BST subtrees: 4.