Algorithms: Mirror a Binary tree using python

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

If you want to learn data structures in python you can read the below books.

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 cloud infrastructure engineer and a full stack web developer and blogger. Sportsperson by heart and loves football. Scale is something he loves to work for and always keen to learn new tech. Experienced with CI/CD, distributed cloud infrastructure, build systems and lot of SRE Stuff.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.