forked from anoopj/pysplay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
splay.py
138 lines (121 loc) · 3.53 KB
/
splay.py
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
131
132
133
134
135
136
137
138
class Node:
def __init__(self, key, data=None):
self.key = key
self.left = self.right = None
self.data = data
def equals(self, node):
return self.key == node.key
class SplayTree:
def __init__(self):
self.root = None
self.header = Node(None) #For splay()
def insert(self, key,data=None):
if (self.root == None):
self.root = Node(key,data)
return
self.splay(key)
if self.root.key == key:
# If the key is already there in the tree, don't do anything.
return
n = Node(key,data)
if key < self.root.key:
n.left = self.root.left
n.right = self.root
self.root.left = None
else:
n.right = self.root.right
n.left = self.root
self.root.right = None
self.root = n
def remove(self, key):
self.splay(key)
if key != self.root.key:
raise 'key not found in tree'
rt = self.root
# Now delete the root.
if self.root.left== None:
self.root = self.root.right
else:
x = self.root.right
self.root = self.root.left
self.splay(key)
self.root.right = x
return rt
def findMin(self):
if self.root == None:
return None
x = self.root
while x.left != None:
x = x.left
self.splay(x.key)
return x
def findMax(self):
if self.root == None:
return None
x = self.root
while (x.right != None):
x = x.right
self.splay(x.key)
return x
def find(self, key):
if self.root == None:
return None
self.splay(key)
if self.root.key != key:
return None
return self.root
def isEmpty(self):
return self.root == None
def furthestNode(self):
self.furthesth = 0
self.furthestnode = self.root
self.heightNode(self.root)
return self.furthestnode
def heightNode(self, x,h=0):
if x.right ==None and x.left == None: #i'm a leaf
if self.furthesth<h+1:
self.furthesth = h+1
self.furthestnode =x
return
if x.right != None:
self.heightNode(x.right, h+1)
if x.left != None:
self.heightNode(x.left, h+1)
def splay(self, key):
l = r = self.header
t = self.root
self.header.left = self.header.right = None
while True:
if key < t.key:
if t.left == None:
break
if key < t.left.key:
y = t.left
t.left = y.right
y.right = t
t = y
if t.left == None:
break
r.left = t
r = t
t = t.left
elif key > t.key:
if t.right == None:
break
if key > t.right.key:
y = t.right
t.right = y.left
y.left = t
t = y
if t.right == None:
break
l.right = t
l = t
t = t.right
else:
break
l.right = t.left
r.left = t.right
t.left = self.header.right
t.right = self.header.left
self.root = t