Skip to content

Commit 64bd91a

Browse files
authored
Convert a Binary Tree into its Mirror Tree
Convert a Binary Tree into its Mirror Tree
1 parent 923e4d6 commit 64bd91a

1 file changed

Lines changed: 81 additions & 0 deletions

File tree

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# Python3 program to convert a binary
2+
# tree to its mirror
3+
4+
# Utility function to create a new
5+
# tree node
6+
class newNode:
7+
def __init__(self,data):
8+
self.data = data
9+
self.left = self.right = None
10+
11+
""" Change a tree so that the roles of the
12+
left and right pointers are swapped at
13+
every node.
14+
15+
So the tree...
16+
4
17+
/ \
18+
2 5
19+
/ \
20+
1 3
21+
22+
is changed to...
23+
4
24+
/ \
25+
5 2
26+
/ \
27+
3 1
28+
"""
29+
def mirror(node):
30+
31+
if (node == None):
32+
return
33+
else:
34+
35+
temp = node
36+
37+
""" do the subtrees """
38+
mirror(node.left)
39+
mirror(node.right)
40+
41+
""" swap the pointers in this node """
42+
temp = node.left
43+
node.left = node.right
44+
node.right = temp
45+
46+
""" Helper function to print Inorder traversal."""
47+
def inOrder(node) :
48+
49+
if (node == None):
50+
return
51+
52+
inOrder(node.left)
53+
print(node.data, end = " ")
54+
inOrder(node.right)
55+
56+
# Driver code
57+
if __name__ =="__main__":
58+
59+
root = newNode(1)
60+
root.left = newNode(2)
61+
root.right = newNode(3)
62+
root.left.left = newNode(4)
63+
root.left.right = newNode(5)
64+
65+
""" Print inorder traversal of
66+
the input tree """
67+
print("Inorder traversal of the",
68+
"constructed tree is")
69+
inOrder(root)
70+
71+
""" Convert tree to its mirror """
72+
mirror(root)
73+
74+
""" Print inorder traversal of
75+
the mirror tree """
76+
print("\nInorder traversal of",
77+
"the mirror treeis ")
78+
inOrder(root)
79+
80+
# This code is contributed by
81+
# Shubham Singh(SHUBHAMSINGH10)

0 commit comments

Comments
 (0)