Insertion in Splay Tree

Last Updated : 23 Jul, 2025

It is recommended to refer following post as prerequisite of this post.
Splay Tree | Set 1 (Search)
As discussed in the previous post, Splay tree is a self-balancing data structure where the last accessed key is always at root. The insert operation is similar to Binary Search Tree insert with additional steps to make sure that the newly inserted key becomes the new root.
Following are different cases to insert a key k in splay tree.
1) Root is NULL: We simply allocate a new node and return it as root.
2) Splay the given key k. If k is already 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 same as k, don't do anything as k is already present.
4) Else allocate memory for new node and compare root's key with k. 
.......4.a) If k is smaller than root's key, make root as right child of new node, copy left child of root as left child of new node and make left child of root as NULL. 
.......4.b) If k is greater than root's key, make root as left child of new node, copy right child of root as right child of new node and make right child of root as NULL.
5) Return new node as new root of tree.
Example: 
 

 
100 [20] 25
/ \ \ / \
50 200 50 20 50
/ insert(25) / \ insert(25) / \
40 ======> 30 100 ========> 30 100
/ 1. Splay(25) \ \ 2. insert 25 \ \
30 40 200 40 200
/
[20]


 

C++
#include <bits/stdc++.h>
using namespace std;

// An AVL tree node 
class node 
{ 
    public:
    int key; 
    node *left, *right; 
}; 

/* Helper function that allocates 
a new node with the given key and 
    NULL left and right pointers. */
node* newNode(int key) 
{ 
    node* Node = new 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. 
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 
// See the diagram given above. 
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 
node *splay(node *root, int key) 
{ 
    // Base cases: root is NULL or 
    // key is present at root 
    if (root == NULL ||