Binary Search Trees

Use the BST ordering property for search, insert, delete, validation, kth smallest and floor and ceiling queries.

Intermediate · about 6 hours · difficulty 3/5

Learn first: Binary Tree Traversals

A BST keeps every left subtree smaller and every right subtree larger than the node. That property lets you discard half the tree at each step when it is balanced.

Operations

  • Search, insert and delete in O(h). Delete has three cases: leaf, one child, two children (replace with inorder successor).
  • Inorder traversal of a BST is sorted. Many problems reduce to this fact.
  • Floor and ceiling of a key, inorder successor and predecessor.

Key patterns

  • Validate BST by passing a (min, max) range down, not by comparing only with direct children.
  • Kth Smallest Element: inorder traversal with a counter.
  • LCA in a BST: walk down; split point is the answer.
  • Build from sorted array: pick the middle as root for a balanced tree.
  • Two Sum in a BST: inorder to array plus two pointers, or a BST iterator from both ends.
  • BST Iterator: controlled inorder with a stack, O(h) memory.

Balanced trees

Know that AVL and red-black trees keep height O(log n) and that C++ set and map, and Java TreeMap, are red-black trees. You will rarely implement one in an interview.

Pitfalls

  • Checking only node.left.val < node.val, which misses deeper violations.
  • Assuming O(log n) on a skewed BST, which is O(n).

You are ready to move on when you can delete a node with two children and validate a BST using ranges.

Key concepts

  • BST property and search
  • Insert and delete
  • Validate BST with ranges
  • Inorder gives sorted order
  • Floor, ceil, successor
  • BST iterator
  • AVL and red-black trees

Mini project

Solve these 10 in 7 days, log time and pattern: Search in a BST, Insert into a BST, Delete Node in a BST, Validate Binary Search Tree, Kth Smallest Element in a BST, Lowest Common Ancestor of a BST, Convert Sorted Array to BST, Construct BST from Preorder Traversal, BST Iterator, Two Sum IV - Input is a BST.

Check yourself

Give a small tree where every node satisfies left < node < right with its direct children but the tree is not a valid BST.

Free resources