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 keykeynull
Example 1
Output: [5, 4, 6, 2, null, null, 7]
Explanation: 3 has two children, and 4 takes its place.
Example 2
Output: [5, 3, 6, 2, 4, null, 7]
Explanation: 0 is not in the tree, so nothing changes.
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.
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
Finding the node
Where can keykeydeleteNode(root, key)root.leftkeyroot.right
If a call reaches a missing child, nullkey
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)null
What replaces the node
Which node takes the place of the removed one? A leaf is replaced by nothing, so the call returns nullnull
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
- First, if
isroot , the search has gone past the bottom of the tree without meetingnull , so returnkey .null - If
is smaller than the value stored inkey ,root , delete it from the left subtree withroot.val and store the result indeleteNode(root.left, key) . Ifroot.left is larger, do the same on the right withkey .root.right - Otherwise
holdsroot . Ifkey isroot.left , returnnull , and ifroot.right isroot.right , returnnull . The returned child moves up into the place ofroot.left .root - With two children, start a variable
atsuccessor and move it left whileroot.right is notsuccessor.left . Copynull intosuccessor.val , then remove the old copy withroot.val .root.right = deleteNode(root.right, successor.val) - Finally, return
, so the caller keeps its link to this node.root
The class also holds a small TreeNodebuildshow
The main
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:
[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][5, 3, 6, 2, 4][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]
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]deleteNode(root.right, successor.val)
Complexity
The work is one walk down the tree to key
- 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: