-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsplaytree.java
More file actions
130 lines (124 loc) · 1.74 KB
/
splaytree.java
File metadata and controls
130 lines (124 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
class node{
int data;
node left , right, parent;
node(int data)
{
this.data=data;
left=right=parent=null;
}
}
class splaytree{
node root;
splaytree()
{
root=null;
}
void insert(int data){
node p=null;
node z=root;
while(z!=null){
p=z;
if(z.data<data)
z=z.right;
else
z=z.left;
}
z=new node(data);
z.parent=p;
if(p==null)
root=z;
else{
if(p.data<z.data)
p.right=z;
else
p.left=z;
}
splay(z);
}
void splay(node z){
while(z.parent!=null){
if(z.parent.parent==null){
if(z.parent.left==z)
rightrotate(z.parent);
else
leftrotate(z.parent);
}
else{
if(z.parent.left==z && z.parent==z.parent.parent.left){
rightrotate(z.parent.parent);
rightrotate(z.parent);
}
else if(z.parent.right==z && z.parent==z.parent.parent.right){
leftrotate(z.parent.parent);
leftrotate(z.parent);
}
else if(z==z.parent.left && z.parent.parent.right==z.parent)
{
rightrotate(z.parent);
leftrotate(z.parent);
}
else{
leftrotate(z.parent);
rightrotate(z.parent);
}
}
}
}
public void leftrotate(node x){
node y=x.right;
if(y!=null)
y.left=x.right;
if(y.left!=null)
y.left.parent=x;
y.parent=x.parent;
if(x.parent==null)
root=y;
else if(x.parent.right==x)
x.parent.right=y;
else
x.parent.left=y;
y.left=x;
x.parent=y;
}
public void rightrotate(node x)
{
node y=x.left;
if(y!=null)
y.right=x.left;
if(y.right!=null)
y.right.parent=x;
y.parent=x.parent;
if(x.parent==null)
{
root=y;
}
else if(x.parent.left==x)
{
x.parent.left=y;
}
else {
x.parent.right=y;
}
y.right=x;
x.parent=y;
}
node getroot(){
return root;
}
void preorder(node root){
node curr=root;
if(curr!=null){
System.out.println(""+curr.data);
preorder(curr.left);
preorder(curr.right);
}
}
public static void main(String args[]){
splaytree s=new splaytree();
s.insert(10);
s.insert(20);
s.insert(30);
s.insert(40);
s.preorder(s.getroot());
}
}