Delete Node in a BST

Remove a value from a binary search tree so that smaller values still sit on the left and larger ones on the right.

Given the root of a binary search tree and a number key, delete the node that holds key, if there is one, and return the root of the tree afterwards. The result must still be a binary search tree. Trees are written row by row, top to bottom and left to right, with null where a child is missing.

Example 1
Input: root = [5, 3, 6, 2, 4, null, 7], key = 3
Output: [5, 4, 6, 2, null, null, 7]
Explanation: 3 has two children, and 4 takes its place.
Example 2
Input: root = [5, 3, 6, 2, 4, null, 7], key = 0
Output: [5, 3, 6, 2, 4, null, 7]
Explanation: 0 is not in the tree, so nothing changes.
Solution

The Idea

Taking a number out of a sorted row is easy: you remove it and close the gap. A binary search tree also keeps numbers in order, but in branches instead of a row. In Example 1, the node at the top, called the root, holds 5. Its left child 3 and the nodes below 3 are all smaller than 5. Its right child 6 and the 7 below it are all larger.

The same rule holds at every node: 3 has 2 on its left and 4 on its right. A tree that keeps this rule everywhere is called a binary search tree, or BST. A node together with all the nodes below it is called a subtree, so 3, 2 and 4 form the left subtree of 5.

Finding 3 is quick. 3 is smaller than 5, so it can only be in the left subtree, and there it is. Removing it is the harder part. A node with no children, such as 7, is called a leaf, and it can simply be cut off. Node 6 has one child, 7, so 7 can move up into the place of 6. But 3 has two children, 2 and 4, and its parent 5 has only one left link to give them. So which value should take the place of 3?

That value must be larger than every value in the left subtree of 3, and smaller than every other value in its right subtree. The smallest value in the right subtree fits both: here that is 4. It is called the successor of 3, because it comes right after 3 in sorted order. Look at the picture below.

Deleting key 3 from the tree 5, 3, 6, 2, 4, 7. Node 3 has two children, so its successor 4, the smallest value on its right, is copied up into it and the old 4 is deleted. The tree becomes 5, 4, 6, 2, null, null, 7.

In the tree marked before, key 3 is orange and successor 4 is green. The arrow labelled copy 4 up writes 4 into the node that held 3. The value 4 now appears twice, so the old 4 is deleted, which is easy because it is a leaf. The tree marked after is the output of Example 1, and it keeps the rule: 2 is left of 4, and 4 is left of 5.

So deleting a node with two children turns into deleting its successor instead. And the successor never has a left child, since anything on its left would be smaller still, so that second delete is always one of the easy cases.

Solution Approach

Turning that idea into code means settling three things: how to reach the node that holds key, how its parent gets linked to whatever replaces it, and what replaces it, which depends on how many children it has.

Finding the node

Where can key be? At each node, comparing key with the node's value tells us which subtree to search, just as finding 3 went left at 5. A method that calls itself, a recursive method, fits this well: deleteNode(root, key) calls itself on root.left when key is smaller and on root.right when it is larger.

If a call reaches a missing child, null, then key is not in the tree, as in Example 2, and nothing changes. A search that only goes down one side at each node never looks at the other side, so it touches one node per level.

Linking the parent to the replacement

Once a node is removed, how does its parent find out? Each call returns the root of the subtree it was given, after the delete. The parent stores that value in its own link: root.left = deleteNode(root.left, key). If the child was removed, the link now points at its replacement, or at null. A subtree that did not change returns its own root, so the link stays as it was.

What replaces the node

Which node takes the place of the removed one? A leaf is replaced by nothing, so the call returns null. A node with one child is replaced by that child, since the whole subtree below the child was already on the correct side of the parent. One check covers both: if the left child is missing, return the right child, which is null for a leaf. If only the right child is missing, return the left child.

A node with two children keeps its place in the tree but takes the value of its successor. To find the successor, step once to the right, then keep going left until there is no left child. Then delete that value from the right subtree with the same method. The successor has no left child, so that call ends in the leaf or one-child case.

Java Solution

The method deleteNode works in these steps:

  1. First, if root is null, the search has gone past the bottom of the tree without meeting key, so return null.
  2. If key is smaller than the value stored in root, root.val, delete it from the left subtree with deleteNode(root.left, key) and store the result in root.left. If key is larger, do the same on the right with root.right.
  3. Otherwise root holds key. If root.left is null, return root.right, and if root.right is null, return root.left. The returned child moves up into the place of root.
  4. With two children, start a variable successor at root.right and move it left while successor.left is not null. Copy successor.val into root.val, then remove the old copy with root.right = deleteNode(root.right, successor.val).
  5. Finally, return root, so the caller keeps its link to this node.

The class also holds a small TreeNode class and two helpers: build makes a tree from the row-by-row form, and show prints a tree in that same form.

The main method runs both examples, then deletes a leaf (7), a node with one child (6) and the root (5), all from the tree of Example 1. It ends with the only node of a one-node tree and a key in an empty tree.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class DeleteNodeInBST {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return null;                          // key is not in this subtree
        }
        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;                // no left child: the right side moves up
            }
            if (root.right == null) {
                return root.left;                 // no right child: the left side moves up
            }
            TreeNode successor = root.right;      // two children: smallest value on the right
            while (successor.left != null) {
                successor = successor.left;
            }
            root.val = successor.val;
            root.right = deleteNode(root.right, successor.val);   // remove the successor
        }
        return root;
    }

    // Builds a tree from the row-by-row form, with null for a missing child.
    static TreeNode build(Integer... values) {
        if (values.length == 0 || values[0] == null) {
            return null;
        }
        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        int i = 1;
        while (i < values.length) {
            TreeNode node = queue.poll();
            if (values[i] != null) {
                node.left = new TreeNode(values[i]);
                queue.add(node.left);
            }
            i++;
            if (i < values.length && values[i] != null) {
                node.right = new TreeNode(values[i]);
                queue.add(node.right);
            }
            i++;
        }
        return root;
    }

    // Prints a tree in the same row-by-row form, without trailing nulls.
    static String show(TreeNode root) {
        List<Integer> out = new ArrayList<>();
        List<TreeNode> queue = new ArrayList<>();
        queue.add(root);
        for (int i = 0; i < queue.size(); i++) {
            TreeNode node = queue.get(i);
            out.add(node == null ? null : node.val);
            if (node != null) {
                queue.add(node.left);
                queue.add(node.right);
            }
        }
        while (!out.isEmpty() && out.get(out.size() - 1) == null) {
            out.remove(out.size() - 1);
        }
        return out.toString();
    }

    public static void main(String[] args) {
        System.out.println(show(deleteNode(build(5, 3, 6, 2, 4, null, 7), 3)));
        System.out.println(show(deleteNode(build(5, 3, 6, 2, 4, null, 7), 0)));
        System.out.println(show(deleteNode(build(5, 3, 6, 2, 4, null, 7), 7)));  // a leaf
        System.out.println(show(deleteNode(build(5, 3, 6, 2, 4, null, 7), 6)));  // one child
        System.out.println(show(deleteNode(build(5, 3, 6, 2, 4, null, 7), 5)));  // the root
        System.out.println(show(deleteNode(build(1), 1)));                       // only node
        System.out.println(show(deleteNode(build(), 1)));                        // empty tree
    }
}

Running it prints:

Output
[5, 4, 6, 2, null, null, 7]
[5, 3, 6, 2, 4, null, 7]
[5, 3, 6, 2, 4]
[5, 3, 7, 2, 4]
[6, 3, 7, 2, 4]
[]
[]

The first line, [5, 4, 6, 2, null, null, 7], is Example 1: 4 moved up into the place of 3. The second line is the unchanged tree of Example 2. Deleting the leaf 7 gives [5, 3, 6, 2, 4], and deleting 6 lifts its child 7 into its place, [5, 3, 7, 2, 4].

The fifth line deletes the root. 5 has two children, so its successor 6 is copied up and the old 6 is deleted. That old 6 has a right child, 7, so the second delete is the one-child case and 7 moves up, giving [6, 3, 7, 2, 4]. The last two lines are empty: removing the only node leaves no tree, and an empty tree has nothing to remove.

What if the code copied the successor's value and stopped there? A separate run that does exactly that on Example 1 prints [5, 4, 6, 2, 4, null, 7]. The value 4 now appears twice, once in the old place of 3 and once as the leaf below it. The second call, deleteNode(root.right, successor.val), is what removes that extra 4.

Complexity

The work is one walk down the tree to key, plus, for a node with two children, two more walks down its right subtree: one to find the successor and one to delete it.

  • Time: O(h), because each walk only moves downward, one level per step, so none of them visits more than h nodes, where h is the number of levels in the tree.
  • Space: O(h), because each recursive call waits on the call stack for the call below it, and the calls never go deeper than one path from the root.

In a balanced tree of n nodes, h is about log n. In a tree where every node has only a right child, h is n. Adding a value is the simpler direction: Insert into a BST.