forked from csfx-py/hacktober2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary_Search_tree_basic_operations.py
118 lines (84 loc) · 1.97 KB
/
Binary_Search_tree_basic_operations.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
## All basic BST operations
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
// Add node in BST
def add_child(node,val):
root = node
if val == root.data:
return
if root.data > val:
#add left subtree
if root.left:
add_child(root.left,val)
else:
root.left = Node(val)
else:
#add right subtree
if root.right:
add_child(root.right,val)
else:
root.right = Node(val)
In order traversal - Ascending to Descending Traversal
def inorder_trav(node,ele):
root = node
#ele = []
if not root:
return
inorder_trav(root.left,ele)
ele.append(root.data)
inorder_trav(root.right,ele)
return ele
// Search Element in BST O(LogN)
def search_tree(node,el):
root = node
#print(root.data)
if not root:
return False
if el > root.data:
root = root.right
return search_tree(root,el)
elif el < root.data:
root = root.left
return search_tree(root,el)
else:
return True
#return True
// Minimum Node (Right sub tree's Minimum Element)
def minNode(node):
current = node
while current.left is not None:
current = current.left
return current
// Delete Node in BST
def delete(node,el):
root = node
if el < root.data:
if root.left:
root.left = delete(root.left,el)
elif el > root.data:
if root.right:
root.right = delete(root.right,el)
else:
if root.left is None and root.right is None:
return None
elif root.left is None:
root = root.right
return root
elif root.right is None:
root = root.left
return root
else:
minVal = minNode(root.right)
root.data = minVal.data
root.right = delete(root.right,minVal.data)
return root
ele = [17,8,2,34,1,4,6,9]
node = Node(ele[0])
for i in range(1,len(ele)):
add_child(node,ele[i])
print(inorder_trav(node,[]))
print(search_tree(node,6))
print(inorder_trav(delete(node,6),[]))