-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-search-tree.py
122 lines (96 loc) · 2.99 KB
/
binary-search-tree.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
"""
Implementation of Binary Search Tree
"""
class Node:
def __init__(self, data):
self.data = data
self.leftNode = None
self.rightNode = None
class BST:
def __init__(self):
self.root = None
def insert(self, data):
if not self.root:
self.root = Node(data)
else:
self.insertNode(data, self.root)
def insertNode(self, data, node):
if data < node.data:
if node.leftNode:
self.insertNode(data, node.leftNode)
else:
node.leftNode = Node(data)
else:
if node.rightNode:
self.insertNode(data, node.rightNode)
else:
node.rightNode = Node(data)
def remove(self, data):
if self.root:
self.removeNode(data, self.root)
def removeNode(self, data, node):
if not node:
return node
if data < node.data:
node.leftNode = self.removeNode(data, node.leftNode)
elif data > node.data:
node.rightNode = self.removeNode(data, node.rightNode)
else:
if not node.leftNode and not node.rightNode:
print("removing a leaf node.")
del node
return None
elif not node.leftNode:
print("removing a node with single right child.")
tempNode = node.rightNode
del node
return tempNode
elif not node.rightNode:
print("removing a node with single left child.")
tempNode = node.leftNode
del node
return tempNode
print("removing a node with two children.")
predeccorNode = self.getPredeccorNode(node.leftNode)
node.data = predeccorNode.data
node.leftNode = self.removeNode(predeccorNode.data, node.leftNode)
return node
def getPredeccorNode(self, node):
if node.rightNode:
return self.getPredeccorNode(node.rightNode)
return node
def getMinValue(self):
if self.root:
return self.getMin(self.root)
else:
return "empty tree"
def getMin(self, node):
if node.leftNode:
return self.getMin(node.leftNode)
return node.data
def getMaxValue(self):
if self.root:
return self.getMax(self.root)
else:
return "empty tree"
def getMax(self, node):
if node.rightNode:
return self.getMax(node.rightNode)
return node.data
def traverse(self):
if self.root:
self.traverseInOrder(self.root)
def traverseInOrder(self, node):
if node.leftNode:
self.traverseInOrder(node.leftNode)
print(node.data)
if node.rightNode:
self.traverseInOrder(node.rightNode)
bst = BST()
bst.insert(10)
bst.insert(5)
bst.insert(15)
bst.insert(6)
bst.traverse()
bst.remove(6)
bst.traverse()