Delete a Node from a Binary Search Tree

When we delete a node, there possibilities arise.

1) Node to be deleted is leaf: Simply remove from the tree.

              50                            50
           /     \         delete(20)      /   \
          30      70       --------->    30     70 
         /  \    /  \                     \    /  \ 
       20   40  60   80                   40  60   80

2) Node to be deleted has only one child: Copy the child to the node and delete the child

              50                            50
           /     \         delete(30)      /   \
          30      70       --------->    40     70 
            \    /  \                          /  \ 
            40  60   80                       60   80

3) Node to be deleted has two children: Find inorder successor of the node. Copy contents of the inorder successor to the node and delete the inorder successor. Note that inorder predecessor can also be used.

              50                            60
           /     \         delete(50)      /   \
          40      70       --------->    40    70 
                 /  \                            \ 
                60   80                           80

The important thing to note is, inorder successor is needed only when right child is not empty. In this particular case, inorder successor can be obtained by finding the minimum value in right child of the node.

/* Given a binary search tree and a key, this function deletes the key
   and returns the new root */
public TreeNode deleteBSTNode(TreeNode root, int target) {
	// base case
	if(root == null) return null;
	
	// If the key to be deleted is smaller than the root's key,
    // then it lies in left subtree
	if(target < root.val) {
		root.left = deleteBSTNode(root.left, target);
		
	// If the key to be deleted is greater than the root's key,
    // then it lies in right subtree
	} else if(target > root.val){
		root.right = deleteBSTNode(root.right, target);
		
	// if key is same as root's key, then This is the node
    // to be deleted
	} else {
		if(root.left == null) return root.right;
		if(root.right == null) return root.left;
		
		// Get the in-order successor (smallest in the right subtree)
		// and delete it from the subtree
		TreeNode successor = root.right;
		while(successor.left != null) {
			successor = successor.left;
		}
		// Copy the in-order successor's content to this node
		root.val = successor.val;
		// Delete the in-order successor
		root.right = deleteBSTNode(root.right, successor.val);
	} 
	return root;
}

Reference:

http://algs4.cs.princeton.edu/32bst/BST.java.html

http://geeksquiz.com/binary-search-tree-set-2-delete/

 

你可能感兴趣的:(Binary search)