algoritmauzmanı
Sign in
TREN
6.5Binary Search Tree with Linked Nodes
Lesson 6.5.5

Delete: a node with two children

When a node with two children is deleted, two are left without a parent, and both cannot be linked to the grandparent at once. The way out is to change the value rather than the node: it is replaced by the value that comes right after it in sorted order. This lesson covers the last case of deleting from a , the one exams ask about most.

What you will learn
  • What the inorder successor is and why it is the smallest value in the right subtree
  • How copying the value and deleting the successor turns the hard case into an easy one
  • That the predecessor can be used instead of the successor
7 minTime O(h)Memory O(h)C · Java · Python

1Idea

The value put in place of the deleted one must keep everything on its left smaller and everything on its right larger. The value that does this is the one right after the deleted value in sorted order: the inorder successor. The name comes from , which lists the values in sorted order.

The successor is the smallest value in the right subtree, found with the loop that finds the minimum: one step to the right child, then left as far as you can go. This node has no left child, otherwise there would be a smaller value. So the successor is either a or a node with only a right child.

Deletion finishes in two steps. First the successor's value is copied into the node to delete; the node itself and its links stay where they are. Then that value is deleted from the right subtree. This second deletion falls into one of the easy cases, because the successor has no left child.

Instead of the successor you can use the inorder predecessor, the largest value in the left subtree: one step to the left child, then always right. Both are correct. If an exam does not say which to use, pick the successor as most textbooks do and say so in your answer.

2Step by step

The drawing deletes the root 50 from a tree holding 50, 30, 70, 20, 40, 60, 80 and 65. 50 has two children. The succ pointer sits below its node.

500x1a40600x1a40300x1a90700x1b20200x1b70400x1bc0600x1c10800x1c60650x2c10rootsuccchild
Call stack
  1. Start. We will delete the root, 50.
  2. 50 is found. It has both a left and a right child: neither easy case applies, so the else branch runs.
  3. The successor is searched for. succ first goes down to the right child, 70.
  4. The left of 70 is not empty: succ goes down to 60.
  5. The left of 60 is empty. The loop ends: the successor is 60, the smallest of the values larger than 50.
  6. 60 is copied into the root's data field. The node and its links stay in place; there are now two 60s in the tree.
  7. The extra 60 is deleted from the right subtree: a new delete call opens at 70. 60 is smaller than 70.
  8. 60 is found to the left of 70. It has no left child: this is an easy case.
  9. There is no left child, so the right child 65 is returned and the node of 60 is freed.
  10. The call for 70 writes 65 into its left field. 65 moved up one level.
  11. Result: the root is now 60. The inorder order is 20, 30, 40, 60, 65, 70, 80; the BST rule holds.

struct TreeNode {    int data;    struct TreeNode* left;    struct TreeNode* right;}; struct TreeNode* deleteNode(struct TreeNode* root, int value) {    if (root == NULL) return NULL;                 // value not in the tree    if (value < root->data) {        root->left = deleteNode(root->left, value);   // look left    } else if (value > root->data) {        root->right = deleteNode(root->right, value); // look right    } else if (root->left == NULL) {               // a leaf or only a right child        struct TreeNode* child = root->right;        free(root);        return child;    } else if (root->right == NULL) {              // only a left child        struct TreeNode* child = root->left;        free(root);        return child;    } else {                                       // two children        struct TreeNode* succ = root->right;       // smallest in the right subtree        while (succ->left != NULL)            succ = succ->left;        root->data = succ->data;                   // copy the value        root->right = deleteNode(root->right, root->data); // delete the successor    }    return root;}
class TreeNode {    int data;    TreeNode left, right;    TreeNode(int data) { this.data = data; }} TreeNode deleteNode(TreeNode root, int value) {    if (root == null) return null;                 // value not in the tree    if (value < root.data) {        root.left = deleteNode(root.left, value);     // look left    } else if (value > root.data) {        root.right = deleteNode(root.right, value);   // look right    } else if (root.left == null) {                // a leaf or only a right child        return root.right;    } else if (root.right == null) {               // only a left child        return root.left;    } else {                                       // two children        TreeNode succ = root.right;                // smallest in the right subtree        while (succ.left != null)            succ = succ.left;        root.data = succ.data;                     // copy the value        root.right = deleteNode(root.right, root.data);  // delete the successor    }    return root;}
class TreeNode:    def __init__(self, data):        self.data = data        self.left = None        self.right = None def delete_node(root, value):    if root is None:        return None  # value not in the tree    if value < root.data:        root.left = delete_node(root.left, value)  # look left    elif value > root.data:        root.right = delete_node(root.right, value)  # look right    elif root.left is None:  # a leaf or only a right child        return root.right    elif root.right is None:  # only a left child        return root.left    else:  # two children        succ = root.right  # smallest in the right subtree        while succ.left is not None:            succ = succ.left        root.data = succ.data  # copy the value        root.right = delete_node(root.right, root.data)  # delete the successor    return root

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(h)

Finding the node, finding the successor and deleting the successor are parts of one path from the root down to a leaf. The total work is proportional to the height: O(h). in a balanced tree, in the worst case.

Memory
O(h)

Recursion keeps one call open per level: O(h).

The second delete call never hits the two-children case again, because the successor has no left child. So a deletion looks for a successor at most once.

4Common mistake

A common mistake is deleting the successor from the whole tree instead of the right subtree:

root->data = succ->data;root = deleteNode(root, root->data);   // finds the 60 at the root again

The same value now sits in two places, and a search reaches the upper one first, the node where you just wrote the new value. The deletion falls into the two-children case again and the right node is never deleted. The deletion must always run on root->right. Another mistake is not starting the successor search at the right child: going left from the root finds the minimum, not the successor.

5Try it

If 30 is deleted from the tree 50, 30, 70, 20, 40, 60, 80, which value takes its place? (The successor is used.)

Show the answer

The answer is B. The right subtree of 30 holds only 40. The successor is the smallest value of the right subtree: 40. 40 is copied, and the leaf holding 40 is deleted.

Which is always true for the inorder successor?

Show the answer

The answer is B. The successor is found by going down to the left in the right subtree until you cannot; if it had a left child, there would be a smaller value. It can have a right child, so it need not be a leaf. The right child itself is the successor only when its left is empty.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.