-
Notifications
You must be signed in to change notification settings - Fork 0
/
bst.py
44 lines (40 loc) · 1.31 KB
/
bst.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
class Node():
def __init__(self, value = 0):
self.left = Node()
self.right = Node()
self.value = value
def get_rightmost_left_child(self):
prev, child = self, self.left
while child.right != None:
prev, child = child, child.right
prev.right = child.left
return child
def delete(self):
if self.left == None and self.right == None:
self = None
elif self.left == None:
self = self.left
elif self.right == None:
self = self.right
else:
left, right = self.left, self.right
self = self.get_rightmost_left_child()
self = left, right
def insert(self, value):
if self.value < value:
if self.left != None:
self.left.insert(value)
else:
self.left = Node(value)
elif self.value > value:
if self.right != None:
self.right.insert(value)
else:
self.right = Node(value)
def remove(self, value):
if self.value == value:
self.delete()
elif self.value < value and self.left != None:
self.left.remove(value)
elif self.value > value and self.right != None:
self.right.remove(value)