Return true if the binary tree is a valid binary search tree: every left subtree holds smaller values, every right subtree holds larger values, recursively.
An in-order walk of a BST visits values in strictly increasing order. Walk iteratively with a stack and compare each value with the previous one.
1function isValidBST(root: TreeNode | null): boolean {2const stack: TreeNode[] = [];3let n = root, prev = -Infinity;4while (n || stack.length) {5while (n) { stack.push(n); n = n.left; }6n = stack.pop()!;7if (n.val <= prev) return false;8prev = n.val;9n = n.right;10}11return true;12}
Start at the root.
Space: play/pause · ←/→: step