Validate a binary search tree

Pass an allowed (low, high) range down the tree. Every key must fit its range, not just beat its parent.

Time O(n)Space O(h)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

A BST needs every key in a left subtree to be smaller than the node, and every key in a right subtree to be larger, all the way down, not just for direct children. So carry a range (low, high) into each call. Going left, the node becomes the new upper bound; going right, it becomes the new lower bound. A key outside its range breaks the tree, even when it looks fine next to its parent.

Code

public bool IsValidBST(TreeNode root) =>
    Valid(root, long.MinValue, long.MaxValue);

private bool Valid(TreeNode node, long low, long high) {
    if (node == null) return true;
    if (node.val <= low || node.val >= high) return false;
    return Valid(node.left, low, node.val)
        && Valid(node.right, node.val, high);
}

Tips

In the .NET library

TreeNode is your own class in C#; there is no built-in binary tree type to validate. SortedSet<T> keeps its own red-black tree valid internally, so this check is only needed for trees you build yourself.