-
Notifications
You must be signed in to change notification settings - Fork 0
/
bst.py
81 lines (74 loc) · 2.13 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
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
class Node:
def __init__(self, data, left = None, right = None):
self.data = data
self.left = left
self.right = right
class BST:
def __init__(self):
_root = None
def search(self, key):
cur = self._root
while cur:
if key < cur.data:
cur = cur.left
elif key > cur.data:
cur = cur.right
else:
return cur
return None
def insert(self, key):
if _root == None:
_root = Node(key)
return
cur = self._root
while cur:
if key < cur.data:
if cur.left:
cur = cur.left
else:
cur.left = Node(key)
elif key > cur.data:
if cur.right:
cur = cur.right
else:
cur.right = Node(key)
else:
return
def delete(self, key):
parent, cur = None, self._root
while cur:
if key < cur.data:
parent = cur
cur = cur.left
elif key > cur.data:
parent = cur
cur = cur.right
else:
break
else:
return false
if cur.left is None and cur.right is None:
if parent.left == cur:
parent.left = None
else:
parent.right = None
elif cur.left is not None and cur.right is None:
if parent.left == cur:
parent.left = cur.left
else:
parent.right = cur.left
elif cur.left is None and cur.right is not None:
if parent.left == cur:
parent.left = cur.right
else:
parent.right = cur.right
else:
p, q = cur, cur.right
while q.left:
p = q
q = q.left
cur.data = q.data
if p.right == q:
p.right = None
else:
p.left = None