Command Palette

Search for a command to run...

← All patterns

Pattern · Trees

BST Ordering

Use left < node < right to skip half the tree, and in-order traversal to visit values in sorted order.

Time O(h) for search, O(n) for full checks · Space O(h)

Taught in Module 17: Binary Search Trees

Think of it like this

A library sorted by call number: you know which aisle to skip without looking inside.

Clues that point here

  • → Binary search tree input
  • → Kth smallest
  • → Validate a BST
  • → Search, insert or delete by value

Not this pattern when

  • ✕ The tree is a plain binary tree with no ordering

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

BST Ordering · template
boolean 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);
}
// call: valid(root, Long.MIN_VALUE, Long.MAX_VALUE)

Common versions

  • Validate BST
  • Kth smallest element
  • LCA of a BST
  • Insert into BST
  • Convert sorted array to BST

Practice problems with this pattern

Related patterns