-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbst_operation.py
More file actions
86 lines (67 loc) · 1.84 KB
/
bst_operation.py
File metadata and controls
86 lines (67 loc) · 1.84 KB
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
class BSTNode:
def __init__(self, val) -> None:
self.val = val
self.left = None
self.right = None
def insert_BST(root, data):
if root is None:
return BSTNode(data)
else:
if root.val == data:
return root
elif data > root.val:
root.right = insert_BST(root.right, data)
else:
root.left = insert_BST(root.left, data)
return root
def inorder(root):
if root:
inorder(root.left)
print(root.val, end=" ")
inorder(root.right)
def search_bst(root, data):
while root!=None:
if data < root.val:
return search_bst(root.left, data)
elif data > root.val:
return search_bst(root.right, data)
else:
return print("True")
return print("False")
def find_min_node(node):
cur = node
while cur.left!=None:
cur=cur.left
return cur
def deleteNode(root, data):
if root is None:
return root
if data > root.val:
root.right = deleteNode(root.right, data)
elif data < root.val:
root.left = deleteNode(root.left, data)
else:
if root.left is None and root.right is None:
return None
if root.left is None:
return root.right
elif root.right is None:
return root.left
## when both child nodes are present
min_node = find_min_node(root.right)
root.val = min_node.val
root.right = deleteNode(root.right, min_node.val)
return root
if __name__ =='__main__':
r = BSTNode(50)
r = insert_BST(r, 30)
r = insert_BST(r, 20)
r = insert_BST(r, 40)
r = insert_BST(r, 70)
r = insert_BST(r, 60)
r = insert_BST(r, 80)
# search_bst(r, 90)
inorder(r)
deleteNode(r, 30)
print()
inorder(r)