Algorithms: Mirror a Binary tree using python

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

  1 minute

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.

Algorithms: Mirror a Binary tree using python

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 = data

def inOrder(root):
   if root:
       print (

def mirror(root):
    if root:
        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'
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.

Gaurav Yadav

Gaurav is a Full Stack Web Developer and Blogger. Sportsperson by heart and loves football. He has experience with various frameworks in php, python and javascript. Loves to explore new frameworks and evolve with the trending technology.

Leave a Reply

Your email address will not be published. Required fields are marked *