-
Notifications
You must be signed in to change notification settings - Fork 0
/
BSTDel_SingleLeaf.py
119 lines (92 loc) · 3.04 KB
/
BSTDel_SingleLeaf.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
class Node:
def __init__(self,data):
self.data = data
self.right = None
self.left = None
def __str__(self):
return f"{self.data}"
class Tree:
def __init__(self):
self.root = None
def insert(self, value):
if self.root == None:
self.root = value
else:
self._insert(self.root, value)
def _insert(self, node, value):
if value.data < node.data:
if node.left == None:
node.left = value
else:
self._insert(node.left, value)
else:
if node.right == None:
node.right = value
else:
self._insert(node.right, value)
def search(self, node, value):
if self.root != None:
isFound = self._search(self.root, value)
if isFound == True:
return True
else:
return False
else:
return None
def _search(self, node, value):
if value.data < node.data and node.left != None:
return self._search(node.left, value)
elif value.data > node.data and node.right != None:
return self._search(node.right, value)
elif value.data == node.data:
return True
else:
return False
# printing the binary tree in INORDER
def inorder(self):
self._inorder(self.root)
def _inorder(self, node):
if node != None: # if this none is not given, recursion doesnt
self._inorder(node.left) #even if there is no left or right nodes
print(node.data)
self._inorder(node.right)
def delete(self,num):
"""
This function deletes only the leaf node.
The last nodes which doesnot have children
Just make the repective child of it's
parent None
"""
self._delete(self.root, None, None, num)
def _delete(self,current, previous, isLeft, num):
if current != None:
if num.data == current.data:
if isLeft:
previous.left = None
else:
previous.right = None
elif num.data < current.data:
self._delete(current.left, current, True, num)
else:
self._delete(current.right, current, False, num)
else:
print("Key not found in the tree")
node8 = Node(8)
node9 = Node(9)
node1 = Node(1)
node2 = Node(2)
node11 = Node(11)
node13 = Node(13)
tree = Tree()
tree.insert(node8)
tree.insert(node9)
tree.insert(node1)
tree.insert(node2)
tree.root.data
tree.root.left.data
tree.root.left.right.data
tree.root.right.data
tree.search(tree.root, node13)
tree.inorder()
tree.delete(node2)
tree.inorder()