Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # http://code2begin.blogspot.com
- # Program to make a mirror of the binary tree iteratively
- # node class
- class node:
- def __init__(self, element):
- self.data = element
- self.left = None
- self.right = None
- # function to print the preorder traversal of a binary tree
- def preorder(root):
- if root is None:
- return
- print(root.data, end=" ")
- preorder(root.left)
- preorder(root.right)
- # function to convert tree into mirror tree iteratively
- def mirror_tree(root):
- # if the node is null then return
- if root is None:
- return
- # creating a stack to keep the child pointers
- STACK = list()
- # push root node on the stack
- STACK.append(root)
- while len(STACK) > 0:
- # remove the top node from the stack
- current = STACK[0]
- STACK.remove(STACK[0])
- # swap the left and right nodes
- temp = current.left
- current.left = current.right
- current.right = temp
- # as it is a stack, we push right child node first because we want to access it after operating on the left child
- if current.right is not None:
- STACK.append(current.right)
- if current.left is not None:
- STACK.append(current.left)
- m1 = node(8)
- m1.left = node(3)
- m1.right = node(10)
- m1.left.left = node(1)
- m1.left.right = node(6)
- m1.left.right.left = node(4)
- m1.left.right.right = node(7)
- m1.right.right = node(14)
- m1.right.right.left = node(13)
- m2 = node(8)
- m2.right = node(3)
- m2.left = node(10)
- m2.left.left = node(14)
- m2.right.left = node(6)
- m2.right.right = node(1)
- m2.left.left.right = node(13)
- m2.right.left.left = node(7)
- m2.right.left.right = node(4)
- print("Tree #1 before mirroring : ")
- preorder(m1)
- print("\nTree #1 after mirroring : ")
- mirror_tree(m1)
- preorder(m1)
- print("\n\nTree #2 is mirror of Tree #1 to check the correctness : ")
- print("TREE #1 : ")
- preorder(m1)
- print("\nTREE #2 : ")
- preorder(m2)
Add Comment
Please, Sign In to add comment