forked from codehouseindia/Python-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTreeDeletion.py
83 lines (77 loc) · 1.73 KB
/
BinaryTreeDeletion.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
# Python3 program to illustrate deletion in a Binary Tree
# class to create a node with data, left child and right child.
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
# Inorder traversal of a binary tree
def inorder(temp):
if(not temp):
return
inorder(temp.left)
print(temp.data, end = " ")
inorder(temp.right)
# function to delete the given deepest node (d_node) in binary tree
def deleteDeepest(root,d_node):
q = []
q.append(root)
while(len(q)):
temp = q.pop(0)
if temp is d_node:
temp = None
return
if temp.right:
if temp.right is d_node:
temp.right = None
return
else:
q.append(temp.right)
if temp.left:
if temp.left is d_node:
temp.left = None
return
else:
q.append(temp.left)
# function to delete element in binary tree
def deletion(root, key):
if root == None :
return None
if root.left == None and root.right == None:
if root.key == key :
return None
else :
return root
key_node = None
q = []
q.append(root)
while(len(q)):
temp = q.pop(0)
if temp.data == key:
key_node = temp
if temp.left:
q.append(temp.left)
if temp.right:
q.append(temp.right)
if key_node :
x = temp.data
deleteDeepest(root,temp)
key_node.data = x
return root
# Driver code
if __name__=='__main__':
root = Node(10)
root.left = Node(11)
root.left.left = Node(7)
root.left.right = Node(12)
root.right = Node(9)
root.right.left = Node(15)
root.right.right = Node(8)
print("The tree before the deletion:")
inorder(root)
key = 11
root = deletion(root, key)
print()
print("The tree after the deletion;")
inorder(root)
# This code is contributed by Monika Anandan