# Algorithms: Mirror a Binary tree using python

Algorithms: Mirror a Binary tree using python
5 (100%) 1 vote

In this article we are going to see how we can mirror a binary tree using python. Lets see what are binary tree

# Algorithms: Mirror a Binary tree using python

Binary tree are the tree where one node can have only two child and cannot have more than two. Traversal means visiting all the nodes of the Binary tree.

Lets take the below tree for example.

So we will be writing python code for changing the tree to its mirror.

class Node:
def __init__(self,data):
self.left = None
self.right = None
self.data = data

def inOrder(root):
if root:
inOrder(root.left)
print (root.data)
inOrder(root.right)

def mirror(root):
if root:
mirror(root.left)
mirror(root.right)
root.left, root.right = root.right, root.left

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.right.left = Node(5)

print inOrder(root)
# 4 2 1 5 3
print '\n'
mirror(root)
print inOrder(root)
# 5 3 1 4 2

Thus you can see the mirror trees inorder traversal. It was really simple we just traversed the tree and changed the right subtree with left and left subtree with right subtree.

More article on Algorithms and Data Structure. You can see see all the articles here

Programming Algorithms and Data structure in python

Liked the article, please share and subscribe.