This repository has been archived by the owner on Oct 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 180
/
BinarySearchTree.py
95 lines (70 loc) · 2.31 KB
/
BinarySearchTree.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
class TreeNode:
def __init__(self, val, left = None, right = None, parent = None):
self.val = val
self.leftChild = left
self.rightChild = right
self.parent = parent
def hasLeftChild(self):
return self.leftChild
def hasRightChild(self):
return self.rightChild
def isRoot(self):
return not self.parent
def isLeaf(self):
return not(self.leftChild or self.rightChild)
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, val):
if self.root:
self._insert(val, self.root)
else:
self.root = TreeNode(val)
def _insert(self, val, currentNode):
if val < currentNode.val:
if currentNode.hasLeftChild():
self._insert(val, currentNode.leftChild)
else:
currentNode.leftChild = TreeNode(val, parent = currentNode)
else:
if currentNode.hasRightChild():
self._insert(val, currentNode.rightChild)
else:
currentNode.rightChild = TreeNode(val, parent = currentNode)
# if BST contains node return it
def contains(self, val):
if self.root:
return self._contains(val, self.root)
else:
return None
def _contains(self, val, currentNode):
if not currentNode:
return None
elif val == currentNode.val:
return currentNode
elif val < currentNode:
return self._contains(val, currentNode.leftChild)
else:
return self._contains(val, currentNode.rightChild)
# search for the minimum node
def findMin(self):
if self.root:
return self._findMin(self.root)
else:
return None
def _findMin(self, currentNode):
if currentNode.hasLeftChild():
return self._finMin(currentNode.leftChild)
else:
return currentNode
# search for the maximum node
def findMax(self):
if self.root:
return self._findMax(self.root)
else:
return None
def _findMax(self, currentNode):
if currentNode.hasRightChild():
return _findMax(currentNode.rightChild)
else:
return currentNode