MCPcopy Create free account
hub / github.com/ndleah/python-mini-project / BST

Class BST

Binary_Search_Tree/bst.py:1–86  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class BST:
2
3 def __init__(self,val,left,right):
4 self.val = val
5 self.left = left
6 self.right = right
7
8 def addHelper(self,root,data):
9
10 # case for reaching current leafs, base cases
11 if root.val < data and root.right == None:
12 root.right = BST(data,None,None)
13 return "insertion completed"
14 elif root.val > data and root.left == None:
15 root.left = BST(data,None,None)
16 return "insertion completed"
17
18 # else we continue tracing downwards
19 if root.val < data:
20 return self.add(root.right,data)
21 elif root.val > data:
22 return self.add(root.left,data)
23 else:
24 return "insertion failed: duplicate value"
25
26 def add(self,root,data):
27 if root == None:
28 return "insertion failed: empty root"
29 return self.addHelper(root,data)
30
31 def restructdata(self,root):
32 # base case: we reach a leaf
33 if root == None or (root.left == None and root.right == None):
34 root = None
35 return "restructure finished"
36
37 # need dummy nodes to compare target value to children value
38 v1 = float('-inf')
39 v2 = float('inf')
40 if root.left != None:
41 v1 = root.left.val
42 if root.right != None:
43 v2 = root.right.val
44
45 temp = root.val
46 if v1 > v2 or v2 == float('inf'):
47 root.val = root.left.val
48 root.left.val = temp
49 return self.restructdata(root.left)
50 else:
51 root.val = root.right.val
52 root.right.val = temp
53 return self.restructdata(root.right)
54
55
56 def removeHelper(self,root,data):
57 if root == None:
58 return "deletion failed: could not find value"
59
60 # adhering to typical bst properties

Callers 1

addHelperMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected