m2skills

mirror rec bt python

Jun 4th, 2018
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. # http://code2begin.blogspot.com
  2. # Program to create a mirror of the given binary tree recursively
  3. # node class
  4. class node:
  5.     def __init__(self, element):
  6.         self.data = element
  7.         self.hd = -1
  8.         self.left = None
  9.         self.right = None
  10.  
  11.  
  12. # function to print the preorder traversal of a binary tree
  13. def preorder(root):
  14.     if root is None:
  15.         return
  16.  
  17.     print(root.data, end=" ")
  18.     preorder(root.left)
  19.     preorder(root.right)
  20.  
  21.  
  22. # function to return mirror of the binary tree
  23. def mirror_tree_recursive(root):
  24.     if root is None:
  25.         return
  26.     else:
  27.         # creating mirror using postorder traversal
  28.         mirror_tree_recursive(root.left)
  29.         mirror_tree_recursive(root.right)
  30.  
  31.         temp = root.left
  32.         root.left = root.right
  33.         root.right = temp
  34.  
  35.  
  36.  
  37. # main
  38. # TREE 1
  39. m1 = node(8)
  40. m1.left = node(3)
  41. m1.right = node(10)
  42. m1.left.left = node(1)
  43. m1.left.right = node(6)
  44. m1.left.right.left = node(4)
  45. m1.left.right.right = node(7)
  46. m1.right.right = node(14)
  47. m1.right.right.left = node(13)
  48.  
  49. # TREE 2
  50. m2 = node(8)
  51. m2.right = node(3)
  52. m2.left = node(10)
  53. m2.left.left = node(14)
  54. m2.right.left = node(6)
  55. m2.right.right = node(1)
  56. m2.left.left.right = node(13)
  57. m2.right.left.left = node(7)
  58. m2.right.left.right = node(4)
  59.  
  60.  
  61. print("Tree #1 before mirroring : ")
  62. preorder(m1)
  63. print("\nTree #1 after mirroring : ")
  64. mirror_tree_recursive(m1)
  65. preorder(m1)
  66. print("\n\nTree #2 is mirror of Tree #1 to check the correctness : ")
  67. print("TREE #1 : ")
  68. preorder(m1)
  69. print("\nTREE #2 : ")
  70. preorder(m2)
Add Comment
Please, Sign In to add comment