TREES, TRIES & HEAPS / ALGORITHM BRIEF

Binary search tree

A binary search tree (BST) is a binary tree with an ordering rule: every value in a node's left subtree is smaller than the node, and every value in its right subtree is larger.

IntermediatePhase 04 / Topic 3 of 8Mental modelComplexityEdge cases
01

Overview

A binary search tree (BST) is a binary tree with an ordering rule: every value in a node's left subtree is smaller than the node, and every value in its right subtree is larger. That rule lets search, insert, and delete discard one subtree at each step, just like binary search on a sorted array.

Operations cost O(h), where h is the height. A balanced BST has h = O(log n), but inserting sorted data into a plain BST produces a chain with h = n. That is why production systems use self-balancing trees (see Balanced search trees).

A 'higher or lower' guessing game tree

Every node is a guess. If the target is smaller you go left, if larger you go right. Each answer throws away an entire half of the remaining possibilities, so a well-shaped tree finds any value in a handful of steps.

02

When to use it

  • You need sorted data with fast inserts and deletes (arrays make inserts O(n)).
  • Floor, ceiling, predecessor, successor, or range queries.
  • The problem gives a BST and asks to exploit ordering.
  • Maintaining an ordered set or map (Java TreeMap / TreeSet).
03

Problem patterns it solves

Search / insert / delete

Recognize it when: basic BST operations using the ordering rule.

  • 700. Search in a Binary Search Tree
  • 701. Insert into a Binary Search Tree
  • 450. Delete Node in a BST
Validate with bounds

Recognize it when: check every node lies within (min, max) inherited from ancestors.

  • 98. Validate Binary Search Tree
  • 1373. Maximum Sum BST in Binary Tree
Inorder = sorted

Recognize it when: kth smallest, two sum in BST, minimum difference.

  • 230. Kth Smallest Element in a BST
  • 653. Two Sum IV - Input is a BST
  • 530. Minimum Absolute Difference in BST
LCA using ordering

Recognize it when: split point where p and q go different ways.

  • 235. Lowest Common Ancestor of a BST
Build balanced from sorted

Recognize it when: sorted array or list to a height-balanced BST.

  • 108. Convert Sorted Array to Binary Search Tree
  • 109. Convert Sorted List to Binary Search Tree
Range operations

Recognize it when: sum of values in [low, high], trim to a range.

  • 938. Range Sum of BST
  • 669. Trim a Binary Search Tree
04

Where it is used in real software

Ordered maps in standard libraries

Java TreeMap and TreeSet, C++ std::map and std::set are balanced BSTs (red-black trees) that support floor, ceiling, and ordered iteration.

Database indexes

B-trees generalize BSTs to many keys per node, minimizing disk reads for range queries like WHERE price BETWEEN 10 AND 20.

Schedulers

The Linux Completely Fair Scheduler stores runnable tasks in a red-black tree ordered by virtual runtime and always runs the leftmost task.

Order books

Trading engines keep bids and asks in ordered trees to find the best price and match orders.

05

Key terms

BST property
left subtree < node < right subtree, for every node.
Inorder successor
The next larger value: the leftmost node of the right subtree.
Floor / ceiling
Largest value <= x / smallest value >= x.
Degenerate tree
A BST shaped like a linked list, with O(n) operations.
06

Deleting a node

  1. 1
    Find the node

    Go left if key < node.val, right if larger.

  2. 2
    Case 1: leaf

    Remove it by returning null to the parent.

  3. 3
    Case 2: one child

    Replace the node with its only child.

  4. 4
    Case 3: two children

    Find the inorder successor (smallest in the right subtree), copy its value into the node, then delete the successor from the right subtree.

07

Search for 6 and insert 5

BST: 8 (left 3, right 10); 3 (left 1, right 6); 6 (left 4, right 7)

Step 1 / 7
StepCurrentComparisonMove
Search 186 < 8go left
Search 236 > 3go right
Search 366 = 6found
Insert 185 < 8go left
Insert 235 > 3go right
Insert 365 < 6go left
Insert 445 > 4right is null: attach 5

NOWStep: Search 1 | Current: 8 | Comparison: 6 < 8 | Move: go left

Each step goes down one level, so the cost is the height of the tree. New values are always inserted as leaves.

08

Implementation

function searchBST(root, val) {  let node = root;  while (node && node.val !== val) node = val < node.val ? node.left : node.right;  return node;} function insertIntoBST(root, val) {  if (!root) return new TreeNode(val);  if (val < root.val) root.left = insertIntoBST(root.left, val);  else root.right = insertIntoBST(root.right, val);  return root;} function deleteNode(root, key) {  if (!root) return null;  if (key < root.val) root.left = deleteNode(root.left, key);  else if (key > root.val) root.right = deleteNode(root.right, key);  else {    if (!root.left) return root.right;    if (!root.right) return root.left;    let successor = root.right;    while (successor.left) successor = successor.left;    root.val = successor.val;    root.right = deleteNode(root.right, successor.val);  }  return root;} // Validate with inherited bounds, not just parent comparisonfunction isValidBST(node, low = -Infinity, high = Infinity) {  if (!node) return true;  if (node.val <= low || node.val >= high) return false;  return isValidBST(node.left, low, node.val) && isValidBST(node.right, node.val, high);} function sortedArrayToBST(nums, lo = 0, hi = nums.length - 1) {  if (lo > hi) return null;  const mid = (lo + hi) >> 1;  return new TreeNode(nums[mid], sortedArrayToBST(nums, lo, mid - 1), sortedArrayToBST(nums, mid + 1, hi));}
09

Complexity and performance

Search / insert / deleteO(h)

O(log n) balanced, O(n) degenerate.

Inorder traversalO(n)

Sorted output.

Build from sorted arrayO(n)

Middle element as root, recursively.

SpaceO(n)

Plus O(h) recursion.

10

Trade-offs

BST vs hash map

Hash maps are O(1) average but unordered. BSTs are O(log n) but support ordered iteration, floor, ceiling, and range queries.

BST vs sorted array

A sorted array has faster lookups (cache-friendly binary search) but O(n) inserts. A balanced BST has O(log n) inserts.

Unbalanced risk

A plain BST on sorted or adversarial input degrades to O(n). Use a self-balancing tree in production.

11

Variants and related techniques

Self-balancing BSTs

AVL and red-black trees keep height O(log n) with rotations.

Augmented BST

Store subtree size in each node to answer kth smallest and rank queries in O(log n).

BST iterator

An explicit stack gives amortized O(1) next() in sorted order.

12

Common mistakes

  • Validating only against the parent.

    Fix: A node deep in the left subtree must also be smaller than every ancestor it is left of. Pass bounds down.

  • Duplicates.

    Fix: Decide a rule (go right, or keep a count) and apply it consistently.

  • Integer bounds in Java validation.

    Fix: Use Long or nullable Integer bounds; node values can equal Integer.MIN_VALUE.

13

Interview questions

What is the time complexity of BST operations?

O(h). It is O(log n) when the tree is balanced and O(n) in the worst case, such as after inserting sorted keys.

How do you find the kth smallest element efficiently if it is queried often?

Augment each node with its subtree size. At each node compare k with the left subtree size to decide which way to go, giving O(h) per query.

14

Practice problems

ProblemDifficultyWhat it trains
700. Search in a Binary Search TreeEasyOrdering rule.
108. Convert Sorted Array to Binary Search TreeEasyBalanced construction.
938. Range Sum of BSTEasyPruning with bounds.
98. Validate Binary Search TreeMediumInherited bounds.
450. Delete Node in a BSTMediumThree deletion cases.
235. Lowest Common Ancestor of a BSTMediumSplit point.