-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST.py
111 lines (89 loc) · 2.68 KB
/
BST.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
class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
def insert(root,node):
if root is None:
root = node
else:
if root.val < node.val:
if root.right is None:
root.right = node
else:
insert(root.right, node)
else:
if root.left is None:
root.left = node
else:
insert(root.left, node)
def minValueNode( node):
current = node
# loop down to find the leftmost leaf
while(current.left is not None):
current = current.left
return current
def deleteNode(root, key):
# Base Case
if root is None:
return root
# If the key to be deleted is smaller than the root's
# key then it lies in left subtree
if key < root.val:
root.left = deleteNode(root.left, key)
# If the kye to be delete is greater than the root's key
# then it lies in right subtree
elif(key > root.val):
root.right = deleteNode(root.right, key)
# If key is same as root's key, then this is the node
# to be deleted
else:
# Node with only one child or no child
if root.left is None :
temp = root.right
root = None
return temp
elif root.right is None :
temp = root.left
root = None
return temp
# Node with two children: Get the inorder successor
# (smallest in the right subtree)
temp = minValueNode(root.right)
# Copy the inorder successor's content to this node
root.val = temp.val
# Delete the inorder successor
root.right = deleteNode(root.right , temp.val)
return root
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
def preorder(root):
if root:
print(root.val)
preorder(root.left)
preorder(root.right)
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(root.val)
r = Node(50)
insert(r,Node(30))
insert(r,Node(20))
insert(r,Node(40))
insert(r,Node(70))
insert(r,Node(60))
insert(r,Node(80))
# Print inoder traversal of the BST
print("inorder traversal is:")
inorder(r)
print("preorder traversal is:")
preorder(r)
print("postorder traversal is:")
postorder(r)
deleteNode(r,30)
print("inorder traversal is:")
inorder(r)