Deletion in B-Tree in Java

Deletion In B-Tree:

A  B–Tree can be defined as a multi-way search tree of order m. All the values of a node that appear on the leftmost child of the node are smaller than the first value of that node. Similarly, all the values that appear on the rightmost child of a node are greater than the last value of that node.We will learn the deletion in B-Tree in C++.

deletion in B Tree in java

Deletion In B-Tree In Java

Example:

Let us consider the given tree. From the given tree we are to delete the following elements:

A = 20 , 53 , 89 , 90 , 85.

Assuming we have order = 5; minimum keys = ⌈ m/2⌉ – 1 = 2; maximum keys = ⌈ m/2⌉ + 1 = 4; minimum children = ⌈ m/2⌉ = 3
maximum children = m = 5

B tree Deletion in java

1. If the target key is at the leaf node:

If the target key is at the leaf node, we further study the given data to check if any of the following cases exist:

  • Case 1: If the leaf node consists of the min number of keys according to the given degree/order, then the key is simply deleted from the node.
  • Case 2: If the leaf contains the minimum number of keys, then:
  • Case 2a: The node can borrow a key from the immediate left sibling node,if it has more than the minimum number of keys.The transfer of the keys take place through the parent node, i.e, the maximum key of the left sibling moves upwards and replaces the parent; while the parent key moves down to the target node from where the target key is simply deleted.
  • Case 2b: The node can borrow a key from the immediate right sibling node, if it has more than the minimum number of keys.The transfer of the keys take place through the parent node, i.e, the minimum key of the right sibling moves upwards and replaces the parent; while the parent key moves down to the target node from where the target key is simply deleted.
  • Case 2c: If neither of the siblings have keys more than the minimum number of keys required then, merge the target node with either the left or the right sibling along with the parent key of respective node.

2.If the target key is at the internal node:

If the target key is at an internal node, we further study the given data to check if any of the following cases exist:

  • Case 1: If the left child has more than the minimum number of keys, the target key in the internal node is replaced by its inorder predecessor ,i.e, the largest element of the left child node.
  • Case 2: If the right child has more than the minimum number of keys, the target key in the internal node is replaced by it’s inorder successor ,i.e, the smallest element of the right child node.

Step 1:

  • The first element to be deleted from the tree structure is 20.
  • We can see the key lies in the leaf node.
Btree deletion in java 1

Step 2:

  • The key 20 exists in a leaf node.
  • The node has more than the minimum number of keys required.
  • Thus the key is simply deleted from the node.
  • The tree after deletion is shown as follows.
Btree deletion in java 2

Step 3:

  • The next element to be deleted from the tree is 53.
  • We can see from the image that the key exists in the leaf node.
B Tree - Deletion

Step 4:

  • Since the node in which the target key 53 exists has just the minimum number of keys, we cannot delete it directly.
  • We check if the target node can borrow a key from it’s sibling nodes.
  • Since the target node doesn’t have any right sibling, it borrows from the left sibling node.
  • As we have studied above how the process of borrow and replace takes place, we apply it to the given structure.
B Tree - Deletion 4

Step 5:

  • The key 49 moves upwards to the parent node.
  • The key 50 moves down to the target node.
B Tree - Deletion in java

Step 6:

  • Now, since the target node has keys more than the minimum number of keys required, the key can be deleted directly.
  • The tree structure after deletion is shown as follows.
B Tree - Deletion

Step 7:

  • The next element to be deleted is 89.
  •  The target key lies within a leaf node as seen from the image.
B Tree - Deletion

Step 8: 

  • Again, the target node holds just the minimum number of keys required and hence the node cannot be deleted directly.
  • The target node now has to borrow a key from either of it’s siblings.
  • We check the left sibling; it also holds just the minimum number of keys required.
  • We check the right sibling node; it has one more than the minimum number of nodes  so the target node can borrow a key from it.
B Tree - Deletion

Step 9:

  • The key 93 moves up to the parent node.
  • The parent key 90 moves down to the target node.
B Tree - Deletion

Step 10:

  • Now, as the target node has sufficient number of keys the target key can directly be deleted from the target node.
  • The tree structure after deletion is shown as follows. 
B Tree - Deletion

Step 11:

  • The next key to be deleted is 90.
  • The key exists within a leaf node as shown in the image.
B Tree - Deletion

Step 12:

  • We can see that the target node has just the minimum number of keys.
  • The target node has to borrow a key from either of it’s siblings.
  • Since each of the siblings just have the number of the minimum keys, it cannot borrow the keys directly.
B Tree - Deletion

Step 13:

  • Since the target node cannot borrow from either of the siblings, we merge the target node, either of the sibling node and the corresponding parent to them.
  • The process of merging is shown as follows.
B Tree - Deletion

Step 14:

  • Since the target node now has sufficient number of keys, the target key 90 can be deleted directly.
  • The tree structure after the deletion of the element is shown as follows.
B Tree - Deletion

Step 15:

  • The next target node is 85.
  • Now here the node to be deleted is not a leaf node but an internal node.
B Tree - Deletion

Step 16:

  • In case, when an internal node is to be deleted, we replace the key with it’s inorder predecessor or inorder successor.
  • We can select either of the child nodes if they have sufficient number of keys.
  • But as we can see in this case the target internal node can only borrow from it’s right child, i.e, inorder predecessor.
  • The key 85 moves down to the child node; key 87 moves up to the parent node.
B Tree - Deletion

Step 17:

  • Now, as the target key is moved to the leaf node, it can be simply deleted from the leaf node.
  • The final tree structure after deletion of various nodes and preserving the b-tree properties is shown as follows.
B Tree - Deletion

C Code For Deletion In B-Tree

Run
import java.util.Stack;
class BTree
{
    private int T;
    
    public class Node
    {
        int n;
        int key[] = new int[2 * T - 1];
        Node child[] = new Node[2 * T];
        boolean leaf = true;
    
        public int Find (int k)
        {
            for (int i = 0; i < this.n; i++)
	       {
                if (this.key[i] == k)
	            {
                    return i;
                }
            }
            return -1;
        };
    }
 
    public BTree (int t)
    {
        T = t;
        root = new Node ();
        root.n = 0;
        root.leaf = true;
    } 
 
    private Node root;

    // Search the key
    private Node Search (Node x, int key)
    {
        int i = 0;
        if (x == null)
            return x;
        for (i = 0; i < x.n; i++)
        {
            if (key < x.key[i])
	        {
                break;
            }
            if (key == x.key[i])
	        {
                return x;
            }
        }
        if (x.leaf)
        {
            return null;
        }
        else
        {
            return Search (x.child[i], key);    
        }
    }
    // Split function
    private void Split (Node x, int pos, Node y)
    {
        Node z = new Node ();
        z.leaf = y.leaf;
        z.n = T - 1;

        for (int j = 0; j < T - 1; j++)
        {
            z.key[j] = y.key[j + T];
        } 
        if (!y.leaf)
        {
            for (int j = 0; j < T; j++)
	        {
                z.child[j] = y.child[j + T];
            } 
        }
        y.n = T - 1;
        for (int j = x.n; j >= pos + 1; j--)
        {
            x.child[j + 1] = x.child[j];
        } 
        x.child[pos + 1] = z;
        
        for (int j = x.n - 1; j >= pos; j--)
        {
            x.key[j + 1] = x.key[j];
        } 
        x.key[pos] = y.key[T - 1];
        x.n = x.n + 1;
    } 
    // Insert the key
    public void Insert (final int key)
    {
        Node r = root;
        
        if (r.n == 2 * T - 1)
        {
            Node s = new Node ();
            root = s;
            s.leaf = false;
            s.n = 0;
            s.child[0] = r;
            Split (s, 0, r);
            _Insert (s, key);
        }
        else
        {
            _Insert (r, key);
        }
    }
    
    // Insert the node
    final private void _Insert (Node x, int k)
    {
        if (x.leaf)
        {
            int i = 0;
            for (i = x.n - 1; i >= 0 && k < x.key[i]; i--)
	        {
                x.key[i + 1] = x.key[i];
            }
            x.key[i + 1] = k;
            x.n = x.n + 1;
        }
        else
        {
            int i = 0;
            for (i = x.n - 1; i >= 0 && k < x.key[i]; i--)
	        {
            };
            i++;
            Node tmp = x.child[i];
            
            if (tmp.n == 2 * T - 1)
	        {
                Split (x, i, tmp);
                if (k > x.key[i])
	            {
                    i++;
                }
            }
            _Insert (x.child[i], k);
        }
    }

    public void Show ()
    {
        Show (root);
    }

    private void Remove (Node x, int key)
    {
        int pos = x.Find (key);
        if (pos != -1)
        {
            if (x.leaf)
	        {
                int i = 0;
                for (i = 0; i < x.n && x.key[i] != key; i++)
	            {
                };
                for (; i < x.n; i++)
	            {
                    if (i != 2 * T - 2)
		            {
                        x.key[i] = x.key[i + 1];
                    }
                }
                x.n--;
                return;
            }
            if (!x.leaf)
	        {
                Node pred = x.child[pos];
                int predKey = 0;
                if (pred.n >= T)
	            {
                    for (;;)
		            {
                        if (pred.leaf)
		                {
                            System.out.println (pred.n);
                            predKey = pred.key[pred.n - 1];
                            break;
                        }
            		    else
		                {
                            pred = pred.child[pred.n];
                        }
                    }
                    Remove (pred, predKey);
                    x.key[pos] = predKey;
                    return;
                }
                
                Node nextNode = x.child[pos + 1];
                if (nextNode.n >= T)
	            {  
                    int nextKey = nextNode.key[0];
                    if (!nextNode.leaf)
		            {
                        nextNode = nextNode.child[0];
                        for (;;)
		                {
                            if (nextNode.leaf)
			                {
                                nextKey = nextNode.key[nextNode.n - 1];
                                break;
                            }
                            else
			                {
                                nextNode = nextNode.child[nextNode.n];
                            }
                        }
                    }
                    Remove (nextNode, nextKey);
                    x.key[pos] = nextKey;
                    return;
                }
                int temp = pred.n + 1;
                pred.key[pred.n++] = x.key[pos];
                for (int i = 0, j = pred.n; i < nextNode.n; i++)
	            {
                    pred.key[j++] = nextNode.key[i];
                    pred.n++;
                } 
                for (int i = 0; i < nextNode.n + 1; i++)
	            {
                    pred.child[temp++] = nextNode.child[i];
                } 
                x.child[pos] = pred;
                for (int i = pos; i < x.n; i++)
	            {
                    if (i != 2 * T - 2)
		            {
                        x.key[i] = x.key[i + 1];
                    }
                }
                for (int i = pos + 1; i < x.n + 1; i++)
	            {
                    if (i != 2 * T - 1)
		            {
                        x.child[i] = x.child[i + 1];
                    }
                }
                x.n--;
                if (x.n == 0)
	           {
                    if (x == root)
		            {
                        root = x.child[0];
                    }
                    x = x.child[0];
                }
                Remove (pred, key);
                return;
            }
        }
        else
        {
            for (pos = 0; pos < x.n; pos++)
	        {
                if (x.key[pos] > key)
	            {
                    break;
                }
            }
            Node tmp = x.child[pos];
    
            if (tmp.n >= T)
	        {
                Remove (tmp, key);
                return;
            }
            if (true)
	        {
                Node nb = null;
                int devider = -1;
                if (pos != x.n && x.child[pos + 1].n >= T)
	            {
                    devider = x.key[pos];
                    nb = x.child[pos + 1];
                    x.key[pos] = nb.key[0];
                    tmp.key[tmp.n++] = devider;
                    tmp.child[tmp.n] = nb.child[0];
                
                    for (int i = 1; i < nb.n; i++)
		            {
                        nb.key[i - 1] = nb.key[i];
                    }
                    for (int i = 1; i <= nb.n; i++)
		            {
                        nb.child[i - 1] = nb.child[i];
                    } 
                    nb.n--;
                    Remove (tmp, key);
                    return;
                }
                else if (pos != 0 && x.child[pos - 1].n >= T)
	            {
                    devider = x.key[pos - 1];
                    nb = x.child[pos - 1];
                    x.key[pos - 1] = nb.key[nb.n - 1];
                    Node child = nb.child[nb.n];
                    nb.n--;
                    
                    for (int i = tmp.n; i > 0; i--)
		            {
                        tmp.key[i] = tmp.key[i - 1];
                    } 
                    tmp.key[0] = devider;
		
                    for (int i = tmp.n + 1; i > 0; i--)
		            {
                        tmp.child[i] = tmp.child[i - 1];
                    } 
                    tmp.child[0] = child;
                    tmp.n++;
                    Remove (tmp, key);
                    return;
                }
        	    else
	            {
                    Node lt = null;
                    Node rt = null;
                    boolean last = false;
                    if (pos != x.n)
		            {
                        devider = x.key[pos];
                        lt = x.child[pos];
                        rt = x.child[pos + 1];
                    }	
                    else
		            {
                        devider = x.key[pos - 1];
                        rt = x.child[pos];
                        lt = x.child[pos - 1];
                        last = true;
                        pos--;      
                    }
                    for (int i = pos; i < x.n - 1; i++)
		            {
                        x.key[i] = x.key[i + 1];
                    }
                    for (int i = pos + 1; i < x.n; i++)
		            {
                        x.child[i] = x.child[i + 1];
                    } 
                    x.n--;
                    lt.key[lt.n++] = devider;

                    for (int i = 0, j = lt.n; i < rt.n + 1; i++, j++)
		            {
                        if (i < rt.n)
		                {
                            lt.key[j] = rt.key[i];
                        }
                        lt.child[j] = rt.child[i];
                    }
                    lt.n += rt.n;
                    if (x.n == 0)
		            {
                        if (x == root)
		                {
                            root = x.child[0];
                        }
                        x = x.child[0];
                    }
                    Remove (lt, key);
                    return;
                }
            }
        }
    }
    
    public void Remove (int key)
    {
        Node x = Search (root, key);
        if (x == null)
        {
            return;
        }
        Remove (root, key);
    }
    
    public void Task (int a, int b)
    {
        Stack < Integer > st = new Stack <> ();
        FindKeys (a, b, root, st);
        while (st.isEmpty () == false)
        {
            this.Remove (root, st.pop ());
        }
    }
    
    private void FindKeys (int a, int b, Node x, Stack < Integer > st)
    {
        int i = 0;
        for (i = 0; i < x.n && x.key[i] < b; i++)
        {
            if (x.key[i] > a)
	        {   
                st.push (x.key[i]);
	  
            }
        }
        if (!x.leaf)
        {
            for (int j = 0; j < i + 1; j++)
	        {
                FindKeys (a, b, x.child[j], st);
            } 
        }
    }
    
    public boolean Contain (int k)
    {
        if (this.Search (root, k) != null)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    // Show the node
    private void Show (Node x)
    {
        assert (x == null);
        for (int i = 0; i < x.n; i++)
        {
            System.out.print (x.key[i] + " ");
        }   
        if (!x.leaf)
        {
            for (int i = 0; i < x.n + 1; i++)
	        {
                Show (x.child[i]);
            } 
        }
    } 
}
public class Main{
    
    public static void main (String[]args)
    {
        BTree b = new BTree (3);
        b.Insert (8);
        b.Insert (9);
        b.Insert (10);
        b.Insert (11);
        b.Insert (15);
        b.Insert (20);
        b.Insert (17);

        b.Show ();
        b.Remove (10);

        System.out.println ();
        b.Show ();
    } 
}

Output:

10 8 9 11 15 17 20 
11 8 9 15 17 20 

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

Introduction to Trees

Binary Trees

Binary Search Trees

Traversals

  • Traversal in Trees
  • Tree Traversals: Breadth-First Search (BFS) : C | C++ | Java
  • Tree Traversals: Depth First Search (DFS) : C | C++ | Java
  • Construct a Binary Tree from Postorder and Inorder

B – Trees

AVL Trees

  • AVL Trees
    • AVL Trees: Introduction
    • AVL Tree Insertion : C | C++ | Java
    • AVL Tree Deletion : C | C++ | Java
    • Insertion in a Binary Tree (Level Order) – C | C++ | Java
    • Searching in Binary Tree – C | C++ | Java
    • Searching in a Binary Search Tree – C | C++ | Java

Complete Programs for Trees

  • Depth First Traversals – C | C++ | Java
  • Level Order Traversal – C | C++Java
  • Construct Tree from given Inorder and Preorder traversals – C | C++Java
  • Construct Tree from given Postorder and Inorder traversals – C | C++Java
  • Construct Tree from given Postorder and Preorder traversal – C | C++Java
  • Find size of the Binary tree – C | C++Java
  • Find the height of binary tree – C | C++Java
  • Find maximum in binary tree – C | C++Java
  • Check whether two tree are identical- CC++Java
  • Spiral Order traversal of Tree- CC++Java
  • Level Order Traversal Line by Line – C | C++Java
  • Hand shaking lemma and some Impotant Tree Properties.
  • Check If binary tree if Foldable or not.- CC++Java
  • check whether tree is Symmetric – C| C++Java.
  • Check for Children-Sum in Binary Tree- C|C++Java
  • Sum of all nodes in Binary Tree- CC++ | Java
  • Lowest Common Ancestor in Binary Tree- CC++ | Java

Introduction to Trees

Binary Trees

Binary Search Trees

Traversals

  • Traversal in Trees
  • Tree Traversals: Breadth-First Search (BFS) : C | C++ | Java
  • Tree Traversals: Depth First Search (DFS) : C | C++ | Java
  • Construct a Binary Tree from Postorder and Inorder

B – Trees

AVL Trees

  • AVL Trees
    • AVL Trees: Introduction
    • AVL Tree Insertion :  C | C++ | Java
    • AVL Tree Deletion : C | C++ | Java
    • Insertion in a Binary Tree (Level Order) – C | C++ | Java
    • Searching in Binary Tree – C | C++ | Java
    • Searching in a Binary Search Tree – C | C++ | Java

Complete Programs for Trees

  • Depth First Traversals – C | C++ | Java
  • Level Order Traversal – C | C++Java
  • Construct Tree from given Inorder and Preorder traversals – C | C++Java
  • Construct Tree from given Postorder and Inorder traversals – C | C++Java
  • Construct Tree from given Postorder and Preorder traversal – C | C++Java
  • Find size of the Binary tree – C | C++Java
  • Find the height of binary tree – C | C++Java
  • Find maximum in binary tree – C | C++Java
  • Check whether two tree are identical- CC++Java
  • Spiral Order traversal of Tree- CC++Java
  • Level Order Traversal LIne by Line – C | C++Java
  • Hand shaking lemma and some Impotant Tree Properties.
  • Check If binary tree if Foldable or not.- CC++Java
  • check whether tree is Symmetric  C| C++Java.
  • Check for Children-Sum in Binary Tree- C|C++Java
  • Sum of all nodes in Binary Tree- CC++ | Java
  • Lowest Common Ancestor in Binary Tree. CC++ | Java