↻one more pass.
Trees · Medium

Validate Binary Search Tree: the idea to remember.

Check whether every node in a binary tree satisfies strict BST ordering.

Solve on LeetCode ↗

The core insight

Carry an exclusive lower and upper bound into each subtree, tightening the relevant bound at every node.

Why it works

The bounds summarize all ancestor restrictions, so satisfying them at every node guarantees the entire subtree ordering.

The mistake to avoid

Comparing only immediate children misses ancestor violations. Use long bounds so int minimum and maximum values are allowed.

Time: O(n)Space: O(h) recursion

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

boolean isValidBST(TreeNode root) { return within(root, Long.MIN_VALUE, Long.MAX_VALUE); }
boolean within(TreeNode node, long low, long high) {
    if (node == null) return true;
    if (node.val <= low || node.val >= high) return false;
    return within(node.left, low, node.val) && within(node.right, node.val, high);
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.