11'''
22A binary search Tree
33'''
4-
54class Node :
65
7- def __init__ (self , label ):
6+ def __init__ (self , label , parent ):
87 self .label = label
98 self .left = None
109 self .right = None
10+ #Added in order to delete a node easier
11+ self .parent = parent
1112
1213 def getLabel (self ):
1314 return self .label
@@ -27,6 +28,11 @@ def getRight(self):
2728 def setRight (self , right ):
2829 self .right = right
2930
31+ def getParent (self ):
32+ return self .parent
33+
34+ def setParent (self , parent ):
35+ self .parent = parent
3036
3137class BinarySearchTree :
3238
@@ -35,13 +41,12 @@ def __init__(self):
3541
3642 def insert (self , label ):
3743 # Create a new Node
38- new_node = Node (label )
44+ new_node = Node (label , None )
3945 # If Tree is empty
4046 if self .empty ():
4147 self .root = new_node
4248 else :
4349 #If Tree is not empty
44- parent_node = None
4550 curr_node = self .root
4651 #While we don't get to a leaf
4752 while curr_node is not None :
@@ -58,8 +63,14 @@ def insert(self, label):
5863 if new_node .getLabel () < parent_node .getLabel ():
5964 parent_node .setLeft (new_node )
6065 else :
61- parent_node .setRight (new_node )
62-
66+ parent_node .setRight (new_node )
67+ #Set parent to the new node
68+ new_node .setParent (parent_node )
69+ '''
70+ def delete(self):
71+ if (not self.empty()):
72+ if()
73+ '''
6374 def getNode (self , label ):
6475 curr_node = None
6576 #If the tree is not empty
@@ -78,6 +89,24 @@ def getNode(self, label):
7889 curr_node = curr_node .getRight ()
7990 return curr_node
8091
92+ def getMax (self ):
93+ #We go deep on the right branch
94+ curr_node = None
95+ if (not self .empty ()):
96+ curr_node = self .getRoot ()
97+ while (curr_node .getRight () is not None ):
98+ curr_node = curr_node .getRight ()
99+ return curr_node
100+
101+ def getMin (self ):
102+ #We go deep on the left branch
103+ curr_node = None
104+ if (not self .empty ()):
105+ curr_node = self .getRoot ()
106+ while (curr_node .getLeft () is not None ):
107+ curr_node = curr_node .getLeft ()
108+ return curr_node
109+
81110 def empty (self ):
82111 if self .root is None :
83112 return True
@@ -92,19 +121,19 @@ def preShow(self, curr_node):
92121 def getRoot (self ):
93122 return self .root
94123
95- '''
96- Example
97- 8
98- / \
99- 3 10
100- / \ \
101- 1 6 14
102- / \ /
103- 4 7 13
104- '''
105124
125+ def testBinarySearchTree ():
126+ '''
127+ Example
128+ 8
129+ / \
130+ 3 10
131+ / \ \
132+ 1 6 14
133+ / \ /
134+ 4 7 13
135+ '''
106136
107- if __name__ == "__main__" :
108137 t = BinarySearchTree ()
109138 t .insert (8 )
110139 t .insert (3 )
@@ -128,3 +157,9 @@ def getRoot(self):
128157 else :
129158 print ("The label -1 doesn't exist" )
130159
160+ if (not t .empty ()):
161+ print ("Max Value: " , t .getMax ().getLabel ())
162+ print ("Min Value: " , t .getMin ().getLabel ())
163+
164+ if __name__ == "__main__" :
165+ testBinarySearchTree ()
0 commit comments