Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # http://code2begin.blogspot.com
- # Program to create a mirror of the given binary tree recursively
- # node class
- class node:
- def __init__(self, element):
- self.data = element
- self.hd = -1
- 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 return mirror of the binary tree
- def mirror_tree_recursive(root):
- if root is None:
- return
- else:
- # creating mirror using postorder traversal
- mirror_tree_recursive(root.left)
- mirror_tree_recursive(root.right)
- temp = root.left
- root.left = root.right
- root.right = temp
- # main
- # TREE 1
- 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)
- # TREE 2
- 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_recursive(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