Data Structures Tutorial

Data Structures Tutorial Asymptotic Notation Structure and Union Array Data Structure Linked list Data Structure Type of Linked list Advantages and Disadvantages of linked list Queue Data Structure Implementation of Queue Stack Data Structure Implementation of Stack Sorting Insertion sort Quick sort Selection sort Heap sort Merge sort Bucket sort Count sort Radix sort Shell sort Tree Traversal of the binary tree Binary search tree Graph Spanning tree Linear Search Binary Search Hashing Collision Resolution Techniques

Misc Topic:

Priority Queue in Data Structure Deque in Data Structure Difference Between Linear And Non Linear Data Structures Queue Operations In Data Structure About Data Structures Data Structures Algorithms Types of Data Structures Big O Notations Introduction to Arrays Introduction to 1D-Arrays Operations on 1D-Arrays Introduction to 2D-Arrays Operations on 2D-Arrays Strings in Data Structures String Operations Application of 2D array Bubble Sort Insertion Sort Sorting Algorithms What is DFS Algorithm What Is Graph Data Structure What is the difference between Tree and Graph What is the difference between DFS and BFS Bucket Sort Dijkstra’s vs Bellman-Ford Algorithm Linear Queue Data Structure in C Stack Using Array Stack Using Linked List Recursion in Fibonacci Stack vs Array What is Skewed Binary Tree Primitive Data Structure in C Dynamic memory allocation of structure in C Application of Stack in Data Structures Binary Tree in Data Structures Heap Data Structure Recursion - Factorial and Fibonacci What is B tree what is B+ tree Huffman tree in Data Structures Insertion Sort vs Bubble Sort Adding one to the number represented an array of digits Bitwise Operators and their Important Tricks Blowfish algorithm Bubble Sort vs Selection Sort Hashing and its Applications Heap Sort vs Merge Sort Insertion Sort vs Selection Sort Merge Conflicts and ways to handle them Difference between Stack and Queue AVL tree in data structure c++ Bubble sort algorithm using Javascript Buffer overflow attack with examples Find out the area between two concentric circles Lowest common ancestor in a binary search tree Number of visible boxes putting one inside another Program to calculate the area of the circumcircle of an equilateral triangle Red-black Tree in Data Structures Strictly binary tree in Data Structures 2-3 Trees and Basic Operations on them Asynchronous advantage actor-critic (A3C) Algorithm Bubble Sort vs Heap Sort Digital Search Tree in Data Structures Minimum Spanning Tree Permutation Sort or Bogo Sort Quick Sort vs Merge Sort Boruvkas algorithm Bubble Sort vs Quick Sort Common Operations on various Data Structures Detect and Remove Loop in a Linked List How to Start Learning DSA Print kth least significant bit number Why is Binary Heap Preferred over BST for Priority Queue Bin Packing Problem Binary Tree Inorder Traversal Burning binary tree Equal Sum What is a Threaded Binary Tree? What is a full Binary Tree? Bubble Sort vs Merge Sort B+ Tree Program in Q language Deletion Operation from A B Tree Deletion Operation of the binary search tree in C++ language Does Overloading Work with Inheritance Balanced Binary Tree Binary tree deletion Binary tree insertion Cocktail Sort Comb Sort FIFO approach Operations of B Tree in C++ Language Recaman’s Sequence Tim Sort Understanding Data Processing Applications of trees in data structures Binary Tree Implementation Using Arrays Convert a Binary Tree into a Binary Search Tree Create a binary search tree Horizontal and Vertical Scaling Invert binary tree LCA of binary tree Linked List Representation of Binary Tree Optimal binary search tree in DSA Serialize and Deserialize a Binary Tree Tree terminology in Data structures Vertical Order Traversal of Binary Tree What is a Height-Balanced Tree in Data Structure Convert binary tree to a doubly linked list Fundamental of Algorithms Introduction and Implementation of Bloom Filter Optimal binary search tree using dynamic programming Right side view of binary tree Symmetric binary tree Trim a binary search tree What is a Sparse Matrix in Data Structure What is a Tree in Terms of a Graph What is the Use of Segment Trees in Data Structure What Should We Learn First Trees or Graphs in Data Structures All About Minimum Cost Spanning Trees in Data Structure Convert Binary Tree into a Threaded Binary Tree Difference between Structured and Object-Oriented Analysis FLEX (Fast Lexical Analyzer Generator) Object-Oriented Analysis and Design Sum of Nodes in a Binary Tree What are the types of Trees in Data Structure What is a 2-3 Tree in Data Structure What is a Spanning Tree in Data Structure What is an AVL Tree in Data Structure Given a Binary Tree, Check if it's balanced B Tree in Data Structure Convert Sorted List to Binary Search Tree Flattening a Linked List Given a Perfect Binary Tree, Reverse Alternate Levels Left View of Binary Tree What are Forest Trees in Data Structure Compare Balanced Binary Tree and Complete Binary Tree Diameter of a Binary Tree Given a Binary Tree Check the Zig Zag Traversal Given a Binary Tree Print the Shortest Path Given a Binary Tree Return All Root To Leaf Paths Given a Binary Tree Swap Nodes at K Height Given a Binary Tree Find Its Minimum Depth Given a Binary Tree Print the Pre Order Traversal in Recursive Given a Generate all Structurally Unique Binary Search Trees Perfect Binary Tree Threaded Binary Trees Function to Create a Copy of Binary Search Tree Function to Delete a Leaf Node from a Binary Tree Function to Insert a Node in a Binary Search Tree Given Two Binary Trees, Check if it is Symmetric A Full Binary Tree with n Nodes Applications of Different Linked Lists in Data Structure B+ Tree in Data Structure Construction of B tree in Data Structure Difference between B-tree and Binary Tree Finding Rank in a Binary Search Tree Finding the Maximum Element in a Binary Tree Finding the Minimum and Maximum Value of a Binary Tree Finding the Sum of All Paths in a Binary Tree Time Complexity of Selection Sort in Data Structure How to get Better in Data Structures and Algorithms Binary Tree Leaf Nodes Classification of Data Structure Difference between Static and Dynamic Data Structure Find the Union and Intersection of the Binary Search Tree Find the Vertical Next in a Binary Tree Finding a Deadlock in a Binary Search Tree Finding all Node of k Distance in a Binary Tree Finding Diagonal Sum in a Binary Tree Finding Diagonal Traversal of The Binary Tree Finding In-Order Successor Binary Tree Finding the gcd of Each Sibling of the Binary Tree Greedy Algorithm in Data Structure How to Calculate Space Complexity in Data Structure How to find missing numbers in an Array Kth Ancestor Node of Binary Tree Minimum Depth Binary Tree Mirror Binary Tree in Data Structure Red-Black Tree Insertion Binary Tree to Mirror Image in Data Structure Calculating the Height of a Binary Search Tree in Data Structure Characteristics of Binary Tree in Data Structure Create a Complete Binary Tree from its Linked List Field in Tree Data Structure Find a Specified Element in a binary Search Tree Find Descendant in Tree Data Structure Find Siblings in a Binary Tree Given as an Array Find the Height of a Node in a Binary Tree Find the Second-Largest Element in a Binary Tree Find the Successor Predecessor of a Binary Search Tree Forest of a Tree in Data Structure In Order Traversal of Threaded Binary Tree Introduction to Huffman Coding Limitations of a Binary Search Tree Link State Routing Algorithm in Data Structure Map Reduce Algorithm for Binary Search Tree in Data Structure Non-Binary Tree in Data Structure Quadratic Probing Example in Hashing Scope and Lifetime of Variables in Data Structure Separate Chaining in Data Structure What is Dynamic Data Structure Separate Chaining vs Open Addressing Time and Space Complexity of Linear Data Structures Abstract Data Types in Data Structures Binary Tree to Single Linked List Count the Number of Nodes in the Binary Tree Count Total No. of Ancestors in a Binary Search Tree Elements of Dynamic Programming in Data Structures Find cost of tree with prims algorithm in data structures Find Preorder Successor in a Threaded Binary Tree Find Prime Nodes Sum Count in Non-Binary Tree Find the Right Sibling of a Binary Tree with Parent Pointers Find the Width of the Binary Search Tree Forest trees in Data Structures Free Tree in Data Structures Frequently asked questions in Tree Data Structures Infix, Postfix and Prefix Conversion Time Complexity of Fibonacci Series What is Weighted Graph in Data Structure What is the Advantage of Linear Search?

Splay Tree

Splay Tree

A splay tree is a self-balanced or self-adjusted binary search tree. We can say, Splay Tree is used in some cases where some elements or data are accessed more frequently over other elements or data. The splay tree self-adjusts after the search, insert, and delete operations. Splay trees are better than other trees, where the specific pattern of the sequence are not known. If we talk about the worst-case time complexity of binary search tree operations is O(n) if the tree is skewed and we have other trees like AVL and Red-Black Trees, their worst-case time complexity is O(log n).

What if we want to do better than AVL and Red-Black Trees: -

In the splay tree, we make recently accessed item by an application, as the root of the tree Splay tree is also self-balancing binary search tree like AVL and Red-Black Trees. In the splay tree, we make a recently accessed item by an application as the root of the tree, so if we want to search again that recently accessed item, then it would take O(1) time. The idea behind this is an application; 80% of the access are to 20% of the items. Suppose there are millions of data items and only a few of them are frequently used, so splay tree come into the picture. There are many real-world applications where the splay tree is used, like in the intrusion detection system, which is an important and essential part of the security infrastructure.

Operations on Splay Tree: -

  • Searching: -

The search operation on the splay tree is the same as the binary search tree; it also does splays(move a node to the root). If searching for a node is successful by an application, then that node will be splayed and becomes the new root of the tree. Otherwise, the last not null node is splayed and becomes the new root of the tree. For searching, we need to follow some cases:

  1. If the searched node is root: -

If the node which we are searching for is the root node, then we return the root and do nothing.

2. If the searched node is the child of root:

If the node which we are searching has no grandparent and node is either a left child of the root, then we need to do right rotation (Zig Rotation), or node is a right child of the root, then we need to do left rotation (Zag Rotation).

3. If Node has both parent and grandparent: -

Then some subcases should be followed:

a). Zig - Zig and Zag - Zag: -

If the node which we are searching is the left child of its parent and also the left child of its grandparent, then we have to do two right rotations, or the desired node is the right child of its parent and also the right child of its grandparent then, we have to perform two left rotations.

b). Zig - Zag and Zag - Zig: -                                                                  

If the node which we are searching is the left child of its parent and right child of its grandparent then we have to do left rotation then right rotations or the desired node is right child of its parent and the left child of its grandparent then, we have to perform right rotation and then left rotation.

These operations make the searched node as root and also help to balance the tree.

  • Inserting: -

If we want to insert a key in the splay tree, then we need to follow some cases:

1. If Root is Null: -

We normally make a new node or add a new node and return it as root.

  • If the key already there: -

If present already in the tree then we will make it as the root node and if it is not there, then last accessed not null node becomes the root node.

3. If the root node same as the keywe won’t do anything.     

4. Else we will make new node and compare it with the root node of tree.

  • If key is smaller than the root node, then we will make root node as right child of new node, copy left child of root as left child of the new node and make left child of root as NULL.
  • If key is greater than root node, then we will make root node as left child of new node, and copy right child of root node as right child of new node and make right child of root node as NULL.

5. We need to return new node which we have made as new root of tree.

  • Deletion: -

   1. If Root is NULL: We directly return the root.

2. Else Splay the given key. If key is present, then we will make it as the new root node. If not there, then last accessed not null node will become the new root.

3. If new root node is not same as key, then return the root node as key is not present.

4. Else the key is present.

  • Divide or Split the tree into two trees suppose T1 = root’s left sub-tree and T2 = root’s right sub-tree and delete the root node.
  • Suppose the roots of T1 and T2 be Root1 and Root2 respectively.
  • If Root1 is NULL, then we need to return Root2.
  • Else, Splay the higher value node (node having the maximum value) of T1.
  • After the Splay procedure, make Root2 as the right child of Root1 and return Root1.

Implementation of Splay Tree in C language: -

#include <stdio.h>
 #include <stdlib.h>
 typedef struct node {
 int data;
 struct node *left;
 struct node *right;
 struct node *parent;
 }node;
 typedef struct splay_tree {
 struct node *root;
 }splay_tree;
 node* new_node(int data) {
 node *n = malloc(sizeof(node));
 n -> data = data;
 n -> parent = NULL;
 n -> right = NULL;
 n -> left = NULL;
 return n;
 }
 splay_tree * new_splay_tree() {
 splay_tree * t = malloc(sizeof(splay_tree));
 t -> root = NULL;
 return t;
 }
 node* maximum(splay_tree * t, node * x) {
 while(x -> right != NULL)
   x = x -> right;
 return x;
 }
 void left_rotate(splay_tree * t, node * x)
 {
 node * y = x -> right;
 x -> right = y -> left;
 if(y -> left != NULL)
 {
   y -> left -> parent = x;
 }
 y -> parent = x -> parent;
 if(x -> parent == NULL) { // x is root
   t -> root = y;
 }
 else if(x == x -> parent -> left) { // x is left child
   x -> parent -> left = y;
 }
 else { //x is right child
   x -> parent -> right = y;
 }
 y -> left = x;
 x -> parent = y;
 }
 void right_rotate(splay_tree * t, node * x) {
 node * y = x -> left;
 x -> left = y -> right;
 if(y -> right != NULL) {
   y -> right -> parent = x;
 }
 y -> parent = x -> parent;
 if(x -> parent == NULL) { // x is root
   t -> root = y;
 }
 else if(x == x -> parent -> right)
 { // x is left child
   x -> parent -> right = y;
 }
 else { // x is right child
   x -> parent -> left = y;
 }
 y -> right = x;
 x -> parent = y;
 }
 void splay(splay_tree *t, node *n) {
 while(n -> parent != NULL) { // node is not root
   if(n -> parent == t -> root) { // node is child of root, one rotation
     if(n == n -> parent -> left) {
       right_rotate(t, n -> parent);
     }
     else {
       left_rotate(t, n -> parent);
     }
   }
   else {
     node *p = n -> parent;
     node *g = p -> parent; // grandparent
     if(n -> parent -> left == n && p -> parent -> left == p) { // both are left children
       right_rotate(t, g);
       right_rotate(t, p);
     }
     else if(n -> parent -> right == n && p -> parent -> right == p) { // both are right children
       left_rotate(t, g);
       left_rotate(t, p);
     }
     else if(n -> parent -> right == n && p -> parent -> left == p) {
       left_rotate(t, p);
       right_rotate(t, g);
     }
     else if(n -> parent -> left == n && p -> parent -> right == p) {
       right_rotate(t, p);
       left_rotate(t, g);
     }
   }
 }
 }
 void insert(splay_tree *t, node *n)
 {
 node *y = NULL;
 node *temp = t -> root;
 while(temp != NULL) {
   y = temp;
   if(n -> data < temp -> data)
     temp = temp -> left;
   else
     temp = temp -> right;
 }
 n -> parent = y;
 if(y == NULL) // newly added node is root
   t -> root = n;
 else if(n -> data < y -> data)
   y -> left = n;
 else
   y -> right = n;
 splay(t, n);
 }
 node* search(splay_tree *t, node *n, int x)
 {
 if(x == n -> data)
 {
   splay(t, n);
   return n;
 }
 else if(x < n -> data)
   return search(t, n -> left, x);
 else if(x > n -> data)
   return search(t, n -> right, x);
 else
   return NULL;
 }
 void delete(splay_tree *t, node *n)
 {
 splay(t, n);
 splay_tree *left_subtree = new_splay_tree();
 left_subtree -> root = t -> root -> left;
 if(left_subtree -> root != NULL)
   left_subtree -> root -> parent = NULL;
 splay_tree *right_subtree = new_splay_tree();
 right_subtree -> root = t -> root -> right;
 if(right_subtree -> root != NULL)
   right_subtree -> root -> parent = NULL;
 free(n);
 if(left_subtree -> root != NULL)
 {
   node *m = maximum(left_subtree, left_subtree -> root);
   splay(left_subtree, m);
   left_subtree -> root -> right = right_subtree -> root;
   t -> root = left_subtree -> root;
 }
 else
 {
   t -> root = right_subtree -> root;
 }
 }
 void inorder(splay_tree *t, node *n)
 {
 if(n != NULL) {
   inorder(t, n -> left);
   printf("%d\n", n -> data);
   inorder(t, n -> right);
 }
 }
 int main()
 {
 splay_tree *t = new_splay_tree();
 node *a, *b, *c, *d, *e, *f, *g, *h, *i, *j, *k, *l, *m;
 a = new_node(10);
 b = new_node(20);
 c = new_node(30);
 d = new_node(100);
 e = new_node(90);
 f = new_node(40);
 g = new_node(50);
 h = new_node(60);
 i = new_node(70);
 j = new_node(80);
 k = new_node(150);
 l = new_node(110);
 m = new_node(120);
 insert(t, a);
 insert(t, b);
 insert(t, c);
 insert(t, d);
 insert(t, e);
 insert(t, f);
 insert(t, g);
 insert(t, h);
 insert(t, i);
 insert(t, j);
 insert(t, k);
 insert(t, l);
 insert(t, m);
 delete(t, a);
 delete(t, m);
 inorder(t, t -> root);
 return 0;
 } 

Output: -

Splay Tree

Complexity: -

Time complexity of splay tree operations (e.g. insertion, deletion and searching) is O(log n).

Applications of Splay Tree: -

  • Splay is used to implement look-up table in Network Router.
    • Used to implement cache, memory allocators.
      • Used in Data Compression
      • Used in the gcc compiler