#12
Tree DFS
DFS with boundsDetermine whether a binary tree is a valid binary search tree.
function isValidBST(root: TreeNode | null): boolean {
const check = (node: TreeNode | null, low: number, high: number): boolean => {
if (!node) return true;
if (node.val <= low || node.val >= high) return false;
return check(node.left, low, node.val) && check(node.right, node.val, high);
};
return check(root, -Infinity, Infinity);
}def valid_bst?(node, low = -Float::INFINITY, high = Float::INFINITY)
return true unless node
return false if node.val <= low || node.val >= high
valid_bst?(node.left, low, node.val) && valid_bst?(node.right, node.val, high)
end