Skip to content

Commit

Permalink
Added the comments
Browse files Browse the repository at this point in the history
  • Loading branch information
mvpamansingh committed Feb 15, 2023
1 parent df327b9 commit f5a0df4
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions Java/Trees/splayTree.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

class splayTree {
class Node {
int key;
Node left, right;
int key; // Key value for the node
Node left, right; // Left and right child nodes of the node

public Node(int key) {
this.key = key;
Expand All @@ -16,11 +16,14 @@ public Node(int key) {
public SplayTree() {
root = null;
}

// for searching the node
public Node search(int key) {
return search(root, key);
}

/**
* Splay the node with the given key to the root of the tree.
* If the key is not in the tree, splay the last accessed node to the root.
*/
private Node search(Node root, int key) {
if (root == null || root.key == key) {
return root;
Expand All @@ -32,7 +35,7 @@ private Node search(Node root, int key) {
return search(root.right, key);
}
}

// inserting
public void insert(int key) {
root = insert(root, key);
}
Expand Down Expand Up @@ -60,7 +63,7 @@ private Node insert(Node root, int key) {

return root;
}

// deleting
public void delete(int key) {
root = delete(root, key);
}
Expand Down Expand Up @@ -113,7 +116,7 @@ private Node splay(Node root, int key) {

return root;
}

if (key > root.right.key) {
root.right.right = splay(root.right.right, key);
root = leftRotate(root);
Expand All @@ -126,14 +129,18 @@ private Node splay(Node root, int key) {

return root.right == null ? root : leftRotate(root);
}

/**
* Rotate the given node to the left.
*/
private Node leftRotate(Node x) {
Node y = x.right;
x.right = y.left;
y.left = x;
return y;
}

/**
* Rotate the given node to the right.
*/
private Node rightRotate(Node x) {
Node y = x.left;
x.left = y.right;
Expand Down

0 comments on commit f5a0df4

Please sign in to comment.