Trees & BST · Pattern 5 of 12

BST basics: search, insert, delete and build

At every node, the value you want is either here, on the left or on the right, so you walk one path down. Inorder visits the values in sorted order.

5 variations · 12 problems · 5 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • The input is a BST and you search, insert or delete a value
  • Build a balanced BST from sorted data
  • Something about the sorted order of the values (iterator, swapped nodes, closest values)
  • Sum or count values within a range

The template

BST Basics
TreeNode searchBST(TreeNode root, int val) {
    while (root != null && root.val != val)
        root = val < root.val ? root.left : root.right;     // only one side can hold it
    return root;
}

TreeNode insertIntoBST(TreeNode root, int val) {
    if (root == null) return new TreeNode(val);             // the empty spot is the place
    if (val < root.val) root.left = insertIntoBST(root.left, val);
    else root.right = insertIntoBST(root.right, val);
    return root;
}

TreeNode deleteNode(TreeNode root, int key) {
    if (root == null) 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 == null) return root.right;           // zero or one child
        if (root.right == null) return root.left;
        TreeNode succ = root.right;                         // two children: copy the successor
        while (succ.left != null) succ = succ.left;
        root.val = succ.val;
        root.right = deleteNode(root.right, succ.val);      // then delete it from the right
    }
    return root;
}

The variations

  1. 1Walk one path down

    Compare with the node and go left or right: search and the minimum (keep going left) never look at the other side. Range sum skips a whole subtree when it is entirely out of range.

  2. 2Insert and delete

    Recurse down and re-attach the returned subtree. Insert puts the value at the empty spot it reaches. Delete with two children copies the inorder successor up and deletes it below.

    Now you solve
  3. 3Build a balanced BST

    The middle of a sorted array is the root, the left half builds the left subtree and the right half the right one. To balance an existing BST, read it into a sorted list with inorder first.

  4. 4Inorder is sorted

    Any question about sorted order is an inorder walk. An iterator keeps the iterative inorder stack between calls; swapped nodes show up as places where inorder goes down; the k closest values are a window on the sorted list.

  5. 5More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Delete with two children: replacing the node but forgetting to delete the successor from the right subtree.
  • Forgetting root.left = insert(root.left, val): without the assignment the new node is never attached.
  • Recover BST: two swapped nodes can be next to each other in inorder. Keep the first bad pair and update only the second node on a later drop.
Next: Postorder with multiple return values: tree DP →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.