Open In App

Deletion in Splay Tree

Last Updated : 20 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

It is recommended to refer following post as prerequisite of this post. Splay Tree | Set 1 (Search) Following are the different cases to delete a key k from splay tree.

  1. If Root is NULL: We simply return the root.
  2. Else Splay the given key k. If k is present, then it becomes the new root. If not present, then last accessed leaf node becomes the new root.
  3. If new root’s key is not same as k, then return the root as k is not present.
  4. Else the key k is present.
    • Split the tree into two trees Tree1 = root’s left subtree and Tree2 = root’s right subtree and delete the root node.
    • Let the root’s of Tree1 and Tree2 be Root1 and Root2 respectively.
    • If Root1 is NULL: Return Root2.
    • Else, Splay the maximum node (node having the maximum value) of Tree1.
    • After the Splay procedure, make Root2 as the right child of Root1 and return Root1.

DELETE PROCEDURE 

Implementation:

CPP




// C implementation to delete a node from Splay Tree
#include <stdio.h>
#include <stdlib.h>
 
// An AVL tree node
struct node {
    int key;
    struct node *left, *right;
};
 
/* Helper function that allocates a new node with the given
   key and NULL left and right pointers. */
struct node* newNode(int key)
{
    struct node* node
        = (struct node*)malloc(sizeof(struct node));
    node->key = key;
    node->left = node->right = NULL;
    return (node);
}
 
// A utility function to right rotate subtree rooted with y
// See the diagram given above.
struct node* rightRotate(struct node* x)
{
    struct node* y = x->left;
    x->left = y->right;
    y->right = x;
    return y;
}
 
// A utility function to left rotate subtree rooted with x
// See the diagram given above.
struct node* leftRotate(struct node* x)
{
    struct node* y = x->right;
    x->right = y->left;
    y->left = x;
    return y;
}
 
// This function brings the key at root if key is present in
// tree. If key is not present, then it brings the last
// accessed item at root. This function modifies the tree
// and returns the new root
struct node* splay(struct node* root, int key)
{
    // Base cases: root is NULL or key is present at root
    if (root == NULL || root->key == key)
        return root;
 
    // Key lies in left subtree
    if (root->key > key) {
        // Key is not in tree, we are done
        if (root->left == NULL)
            return root;
 
        // Zig-Zig (Left Left)
        if (root->left->key > key) {
            // First recursively bring the key as root of
            // left-left
            root->left->left = splay(root->left->left, key);
 
            // Do first rotation for root, second rotation
            // is done after else
            root = rightRotate(root);
        }
        else if (root->left->key
                 < key) // Zig-Zag (Left Right)
        {
            // First recursively bring the key as root of
            // left-right
            root->left->right
                = splay(root->left->right, key);
 
            // Do first rotation for root->left
            if (root->left->right != NULL)
                root->left = leftRotate(root->left);
        }
 
        // Do second rotation for root
        return (root->left == NULL) ? root
                                    : rightRotate(root);
    }
    else // Key lies in right subtree
    {
        // Key is not in tree, we are done
        if (root->right == NULL)
            return root;
 
        // Zag-Zig (Right Left)
        if (root->right->key > key) {
            // Bring the key as root of right-left
            root->right->left
                = splay(root->right->left, key);
 
            // Do first rotation for root->right
            if (root->right->left != NULL)
                root->right = rightRotate(root->right);
        }
        else if (root->right->key
                 < key) // Zag-Zag (Right Right)
        {
            // Bring the key as root of right-right and do
            // first rotation
            root->right->right
                = splay(root->right->right, key);
            root = leftRotate(root);
        }
 
        // Do second rotation for root
        return (root->right == NULL) ? root
                                     : leftRotate(root);
    }
}
 
// The delete function for Splay tree. Note that this
// function returns the new root of Splay Tree after
// removing the key
struct node* delete_key(struct node* root, int key)
{
    struct node* temp;
    if (!root)
        return NULL;
 
    // Splay the given key
    root = splay(root, key);
 
    // If key is not present, then
    // return root
    if (key != root->key)
        return root;
 
    // If key is present
    // If left child of root does not exist
    // make root->right as root
    if (!root->left) {
        temp = root;
        root = root->right;
    }
 
    // Else if left child exits
    else {
        temp = root;
 
        /*Note: Since key == root->key,
        so after Splay(key, root->lchild),
        the tree we get will have no right child tree
        and maximum node in left subtree will get splayed*/
        // New root
        root = splay(root->left, key);
 
        // Make right child of previous root as
        // new root's right child
        root->right = temp->right;
    }
 
    // free the previous root node, that is,
    // the node containing the key
    free(temp);
 
    // return root of the new Splay Tree
    return root;
}
 
// A utility function to print preorder traversal of the
// tree. The function also prints height of every node
void preOrder(struct node* root)
{
    if (root != NULL) {
        printf("%d ", root->key);
        preOrder(root->left);
        preOrder(root->right);
    }
}
 
/* Driver program to test above function*/
int main()
{
    // Splay Tree Formation
    struct node* root = newNode(6);
    root->left = newNode(1);
    root->right = newNode(9);
    root->left->right = newNode(4);
    root->left->right->left = newNode(2);
    root->right->left = newNode(7);
 
    int key = 4;
 
    root = delete_key(root, key);
    printf("Preorder traversal of the modified Splay tree "
           "is \n");
    preOrder(root);
    return 0;
}


Java




// Java program to delete a node from Splay Tree
class SplayTree {
    class Node {
        int key;
        Node left, right;
 
        Node(int key) {
            this.key = key;
            left = right = null;
        }
    }
 
    Node root;
 
    // Splay function for splay tree
    private Node splay(Node root, int key) {
        if (root == null || root.key == key)
            return root;
 
        if (root.key > key) {
            if (root.left == null)
                return root;
 
            if (root.left.key > key) {
                root.left.left = splay(root.left.left, key);
                root = rightRotate(root);
            } else if (root.left.key < key) {
                root.left.right = splay(root.left.right, key);
                if (root.left.right != null)
                    root.left = leftRotate(root.left);
            }
 
            return (root.left == null) ? root : rightRotate(root);
        } else {
            if (root.right == null)
                return root;
 
            if (root.right.key > key) {
                root.right.left = splay(root.right.left, key);
                if (root.right.left != null)
                    root.right = rightRotate(root.right);
            } else if (root.right.key < key) {
                root.right.right = splay(root.right.right, key);
                root = leftRotate(root);
            }
 
            return (root.right == null) ? root : leftRotate(root);
        }
    }
 
    // Rotate left at node x
    private Node leftRotate(Node x) {
        Node y = x.right;
        x.right = y.left;
        y.left = x;
        return y;
    }
 
    // Rotate right at node x
    private Node rightRotate(Node x) {
        Node y = x.left;
        x.left = y.right;
        y.right = x;
        return y;
    }
 
    // Function to delete node from tree
    Node delete(Node root, int key) {
        if (root == null)
            return null;
 
        root = splay(root, key);
 
        if (root.key != key)
            return root;
 
        if (root.left == null) {
            root = root.right;
        } else {
            Node temp = root;
            root = splay(root.left, key);
            root.right = temp.right;
        }
 
        return root;
    }
 
    // Preorder traversal
    void preOrder(Node node) {
        if (node != null) {
            System.out.print(node.key + " ");
            preOrder(node.left);
            preOrder(node.right);
        }
    }
 
    // Driver code
    public static void main(String[] args) {
        SplayTree tree = new SplayTree();
        tree.root = tree.new Node(6);
        tree.root.left = tree.new Node(1);
        tree.root.right = tree.new Node(9);
        tree.root.left.right = tree.new Node(4);
        tree.root.left.right.left = tree.new Node(2);
        tree.root.right.left = tree.new Node(7);
         
        int key = 4;
        tree.root = tree.delete(tree.root, key);
 
        System.out.println("Preorder traversal of the modified Splay tree is:");
        tree.preOrder(tree.root);
    }
}
//This code is contribiuted by Prachi.


Python




# An AVL tree node
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
# A utility function to right rotate subtree rooted with y
def rightRotate(x):
    y = x.left
    x.left = y.right
    y.right = x
    return y
 
# A utility function to left rotate subtree rooted with x
def leftRotate(x):
    y = x.right
    x.right = y.left
    y.left = x
    return y
 
# This function brings the key at root if key is present in tree.
# If key is not present, then it brings the last accessed item at root.
# This function modifies the tree and returns the new root
ans=[]
def splay(root, key):
    # Base cases: root is None or key is present at root
    if root is None or root.key == key:
        return root
 
    # Key lies in left subtree
    if root.key > key:
        if root.left is None:
            return root  # Key is not in the tree, we are done
 
        # Zig-Zig (Left Left)
        if root.left.key > key:
            root.left.left = splay(root.left.left, key)
            root = rightRotate(root)
        # Zig-Zag (Left Right)
        elif root.left.key < key:
            root.left.right = splay(root.left.right, key)
            if root.left.right is not None:
                root.left = leftRotate(root.left)
 
        return root if root.left is None else rightRotate(root)
    else# Key lies in right subtree
        if root.right is None:
            return root  # Key is not in the tree, we are done
 
        # Zag-Zig (Right Left)
        if root.right.key > key:
            root.right.left = splay(root.right.left, key)
            if root.right.left is not None:
                root.right = rightRotate(root.right)
        # Zag-Zag (Right Right)
        elif root.right.key < key:
            root.right.right = splay(root.right.right, key)
            root = leftRotate(root)
 
        return root if root.right is None else leftRotate(root)
 
# The delete function for Splay tree. Note that this
# function returns the new root of Splay Tree after removing the key
def delete_key(root, key):
    if root is None:
        return None
 
    root = splay(root, key)  # Splay the given key
 
    if key != root.key:
        return root  # If key is not present, return root
 
    # If key is present
    if root.left is None:
        temp = root
        root = root.right
    else:
        temp = root
        root = splay(root.left, key)
        root.right = temp.right
 
    del temp  # Free the previous root node containing the key
    return root
 
# A utility function to print preorder traversal of the tree
def pre_order(root):
    if root is not None:
        # print(root.key)
        ans.append(root.key)
        pre_order(root.left)
        pre_order(root.right)
 
# Driver code
class_root = Node(6)
class_root.left = Node(1)
class_root.right = Node(9)
class_root.left.right = Node(4)
class_root.left.right.left = Node(2)
class_root.right.left = Node(7)
 
key_val = 4
 
# Delete the node with key_val from the Splay Tree
class_root = delete_key(class_root, key_val)
print("Preorder traversal of the modified Splay tree is")
pre_order(class_root)
print(' '.join(str(x) for x in ans))
 
# This code is contributed by arindam369


C#




using System;
 
// A splay tree node
class Node
{
    public int key;
    public Node left, right;
 
    public Node(int item)
    {
        key = item;
        left = right = null;
    }
}
 
class SplayTree
{
    // Helper function that allocates a new node with the given
    // key and NULL left and right pointers
    static Node NewNode(int key)
    {
        return new Node(key);
    }
 
    // A utility function to right rotate subtree rooted with y
    static Node RightRotate(Node x)
    {
        Node y = x.left;
        x.left = y.right;
        y.right = x;
        return y;
    }
 
    // A utility function to left rotate subtree rooted with x
    static Node LeftRotate(Node x)
    {
        Node y = x.right;
        x.right = y.left;
        y.left = x;
        return y;
    }
 
    // This function brings the key at root if key is present in
    // tree. If key is not present, then it brings the last
    // accessed item at root. This function modifies the tree
    // and returns the new root
    static Node Splay(Node root, int key)
    {
        // Base cases: root is NULL or key is present at root
        if (root == null || root.key == key)
            return root;
 
        // Key lies in left subtree
        if (root.key > key)
        {
            // Key is not in tree, we are done
            if (root.left == null)
                return root;
 
            // Zig-Zig (Left Left)
            if (root.left.key > key)
            {
                // First recursively bring the key as root of
                // left-left
                root.left.left = Splay(root.left.left, key);
 
                // Do first rotation for root, second rotation
                // is done after else
                root = RightRotate(root);
            }
            else if (root.left.key < key) // Zig-Zag (Left Right)
            {
                // First recursively bring the key as root of
                // left-right
                root.left.right = Splay(root.left.right, key);
 
                // Do first rotation for root.left
                if (root.left.right != null)
                    root.left = LeftRotate(root.left);
            }
 
            // Do second rotation for root
            return (root.left == null) ? root : RightRotate(root);
        }
        else // Key lies in right subtree
        {
            // Key is not in tree, we are done
            if (root.right == null)
                return root;
 
            // Zag-Zig (Right Left)
            if (root.right.key > key)
            {
                // Bring the key as root of right-left
                root.right.left = Splay(root.right.left, key);
 
                // Do first rotation for root.right
                if (root.right.left != null)
                    root.right = RightRotate(root.right);
            }
            else if (root.right.key < key) // Zag-Zag (Right Right)
            {
                // Bring the key as root of right-right and do
                // first rotation
                root.right.right = Splay(root.right.right, key);
                root = LeftRotate(root);
            }
 
            // Do second rotation for root
            return (root.right == null) ? root : LeftRotate(root);
        }
    }
 
    // The delete function for Splay tree.
    // Note that this function returns the new root of Splay Tree
    // after removing the key
    static Node DeleteKey(Node root, int key)
    {
        Node temp;
        if (root == null)
            return null;
 
        // Splay the given key
        root = Splay(root, key);
 
        // If key is not present, then return root
        if (key != root.key)
            return root;
 
        // If key is present
        // If left child of root does not exist,
        // make root.right as root
        if (root.left == null)
        {
            temp = root;
            root = root.right;
        }
        // If left child exists
        else
        {
            temp = root;
 
            // Note: Since key == root.key,
            // so after Splay(key, root.left),
            // the tree we get will have no right child tree
            // and maximum node in the left subtree will get splayed
            // New root
            root = Splay(root.left, key);
 
            // Make the right child of the previous root as
            // new root's right child
            root.right = temp.right;
        }
 
        // Free the previous root node, i.e.,
        // the node containing the key
        temp = null;
 
        // Return root of the new Splay Tree
        return root;
    }
 
    // A utility function to print preorder traversal of the tree.
    // The function also prints the height of every node
    static void PreOrder(Node root)
    {
        if (root != null)
        {
            Console.Write(root.key + " ");
            PreOrder(root.left);
            PreOrder(root.right);
        }
    }
 
    // Driver program to test the above functions
    public static void Main()
    {
        // Splay Tree Formation
        Node root = NewNode(6);
        root.left = NewNode(1);
        root.right = NewNode(9);
        root.left.right = NewNode(4);
        root.left.right.left = NewNode(2);
        root.right.left = NewNode(7);
 
        int key = 4;
 
        root = DeleteKey(root, key);
        Console.WriteLine("Preorder traversal of the modified Splay tree is");
        PreOrder(root);
    }
}


Javascript




// JavaScript implementation to delete a node from Splay Tree
// An AVL tree node
class node {
    constructor(key) {
        this.key = key;
        this.left = null;
        this.right = null;
    }
}
 
// Helper function that allocates a new node with the given
// key and NULL left and right pointers.
function newNode(key) {
    return new node(key);
}
 
// A utility function to right rotate subtree rooted with y
function rightRotate(x) {
    const y = x.left;
    x.left = y.right;
    y.right = x;
    return y;
}
 
// A utility function to left rotate subtree rooted with x
function leftRotate(x) {
    const y = x.right;
    x.right = y.left;
    y.left = x;
    return y;
}
 
// This function brings the key at root if key is present in
// tree. If key is not present, then it brings the last
// accessed item at root. This function modifies the tree
// and returns the new root
function splay(root, key) {
    // Base cases: root is NULL or key is present at root
    if (!root || root.key === key)
        return root;
 
    // Key lies in left subtree
    if (root.key > key) {
        // Key is not in tree, we are done
        if (!root.left)
            return root;
 
        // Zig-Zig (Left Left)
        if (root.left.key > key) {
            // First recursively bring the key as root of
            // left-left
            root.left.left = splay(root.left.left, key);
 
            // Do first rotation for root, second rotation
            // is done after else
            root = rightRotate(root);
        } else if (root.left.key < key) {
            // Zig-Zag (Left Right)
            // First recursively bring the key as root of
            // left-right
            root.left.right = splay(root.left.right, key);
 
            // Do first rotation for root.left
            if (root.left.right)
                root.left = leftRotate(root.left);
        }
 
        // Do second rotation for root
        return (root.left) ? rightRotate(root) : root;
    } else {
        // Key lies in right subtree
        // Key is not in tree, we are done
        if (!root.right)
            return root;
 
        // Zag-Zig (Right Left)
        if (root.right.key > key) {
            // Bring the key as root of right-left
            root.right.left = splay(root.right.left, key);
 
            // Do first rotation for root.right
            if (root.right.left)
                root.right = rightRotate(root.right);
        } else if (root.right.key < key) {
            // Zag-Zag (Right Right)
            // Bring the key as root of right-right and do
            // first rotation
            root.right.right = splay(root.right.right, key);
            root = leftRotate(root);
        }
 
        // Do second rotation for root
        return (root.right) ? leftRotate(root) : root;
    }
}
 
// The delete function for Splay tree.
function delete_key(root, key) {
    let temp;
    if (!root)
        return null;
 
    // Splay the given key
    root = splay(root, key);
 
    // If key is not present, then
    // return root
    if (key !== root.key)
        return root;
 
    // If key is present
    // If left child of root does not exist
    // make root.right as root
    if (!root.left) {
        temp = root;
        root = root.right;
    } else {
        temp = root;
 
        /*Note: Since key == root->key,
        so after Splay(key, root->lchild),
        the tree we get will have no right child tree
        and the maximum node in the left subtree will get splayed*/
        // New root
        root = splay(root.left, key);
 
        // Make the right child of the previous root as
        // the new root's right child
        root.right = temp.right;
    }
 
    // free the previous root node, that is,
    // the node containing the key
    temp = null;
 
    // return root of the new Splay Tree
    return root;
}
 
// A utility function to print preorder traversal of the
// tree. The function also prints the height of every node
function preOrder(root) {
    if (root) {
        console.log(root.key);
        preOrder(root.left);
        preOrder(root.right);
    }
}
 
/* Driver program to test above function*/
// Splay Tree Formation
let root = newNode(6);
root.left = newNode(1);
root.right = newNode(9);
root.left.right = newNode(4);
root.left.right.left = newNode(2);
root.right.left = newNode(7);
 
let key = 4;
 
root = delete_key(root, key);
console.log("Preorder traversal of the modified Splay tree is:");
preOrder(root);


Output

Preorder traversal of the modified Splay tree is 
2 1 6 9 7 

References: https://www.geeksforgeeks.org/splay-tree-set-1-insert/ http://courses.cs.washington.edu/courses/cse326/01au/lectures/SplayTrees.ppt 

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads