Skip to content

Validate Binary Search Tree

MediumLeetCode #98Time O(n)Space O(h)

You get the root of a binary tree. Return whether it is a valid binary search tree: for every node, all values in its left subtree are strictly smaller and all values in its right subtree are strictly larger.

root = [5, 1, 4, null, null, 3, 6] -> false

The right child 4 is smaller than the root 5, so the tree is invalid.

The tempting check is local: is left.val < node.val < right.val? That is wrong. In [10, 5, 15, null, null, 6, 20] every parent-child pair looks fine, but 6 sits in the right subtree of 10 and is smaller than 10.

The rule applies to every ancestor, not just the parent. So carry the allowed range down the recursion as (low, high). Going left, the current value becomes the new upper bound. Going right, it becomes the new lower bound. Each node must fall strictly inside its range.

Show solutionHide solution
def is_valid_bst(root: TreeNode | None) -> bool:
def check(node: TreeNode | None, low: float, high: float) -> bool:
if node is None:
return True
if not (low < node.val < high): # strict: equal values are invalid
return False
return check(node.left, low, node.val) and check(node.right, node.val, high)
return check(root, float("-inf"), float("inf"))
  • Time: O(n) — every node is visited once and does O(1) work.
  • Space: O(h) — recursion stack depth equals the tree height h. That is O(log n) for a balanced tree and O(n) for a skewed one.
  • Only comparing with the parent. This passes the easy examples and fails the deep violation above. Always pass bounds down.
  • Equal values are invalid. Use strict comparisons. [2, 2, 2] must return false.
  • Initial bounds. Node values can be the 32-bit int min or max, so starting from Integer.MIN_VALUE and Integer.MAX_VALUE breaks. Use long in Java, or infinities in Python and TypeScript. (You can also use null bounds.)

Kth Smallest Element in a BST (LeetCode 230)

Section titled “Kth Smallest Element in a BST (LeetCode 230)”

Return the k-th smallest value. The trick: an inorder traversal of a BST visits values in sorted order, so stop at the k-th node visited. Validate BST has an inorder version too: the walk must be strictly increasing.

Exactly two nodes were swapped by mistake; fix the tree without changing its shape. The trick: inorder traversal should be increasing. Find the places where it decreases: the first offender is the larger value of the first drop, the second offender is the smaller value of the last drop. Swap their values.

Convert Sorted Array to Binary Search Tree (LeetCode 108)

Section titled “Convert Sorted Array to Binary Search Tree (LeetCode 108)”

Build a height-balanced BST from a sorted array. The trick: pick the middle element as the root and recurse on the left and right halves.