m2skills

mirror iter bt python

Jun 4th, 2018
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. # http://code2begin.blogspot.com
  2. # Program to make a mirror of the binary tree iteratively
  3. # node class
  4. class node:
  5.     def __init__(self, element):
  6.         self.data = element
  7.         self.left = None
  8.         self.right = None
  9.  
  10.  
  11. # function to print the preorder traversal of a binary tree
  12. def preorder(root):
  13.     if root is None:
  14.         return
  15.  
  16.     print(root.data, end=" ")
  17.     preorder(root.left)
  18.     preorder(root.right)
  19.  
  20.  
  21. # function to convert tree into mirror tree iteratively
  22. def mirror_tree(root):
  23.     # if the node is null then return
  24.     if root is None:
  25.         return
  26.  
  27.     # creating a stack to keep the child pointers
  28.     STACK = list()
  29.     # push root node on the stack
  30.     STACK.append(root)
  31.  
  32.     while len(STACK) > 0:
  33.         # remove the top node from the stack
  34.         current = STACK[0]
  35.         STACK.remove(STACK[0])
  36.  
  37.         # swap the left and right nodes
  38.         temp = current.left
  39.         current.left = current.right
  40.         current.right = temp
  41.  
  42.         # as it is a stack, we push right child node first because we want to access it after operating on the left child
  43.         if current.right is not None:
  44.             STACK.append(current.right)
  45.  
  46.         if current.left is not None:
  47.             STACK.append(current.left)
  48.  
  49.  
  50.  
  51. m1 = node(8)
  52. m1.left = node(3)
  53. m1.right = node(10)
  54. m1.left.left = node(1)
  55. m1.left.right = node(6)
  56. m1.left.right.left = node(4)
  57. m1.left.right.right = node(7)
  58. m1.right.right = node(14)
  59. m1.right.right.left = node(13)
  60.  
  61. m2 = node(8)
  62. m2.right = node(3)
  63. m2.left = node(10)
  64. m2.left.left = node(14)
  65. m2.right.left = node(6)
  66. m2.right.right = node(1)
  67. m2.left.left.right = node(13)
  68. m2.right.left.left = node(7)
  69. m2.right.left.right = node(4)
  70.  
  71. print("Tree #1 before mirroring : ")
  72. preorder(m1)
  73. print("\nTree #1 after mirroring : ")
  74. mirror_tree(m1)
  75. preorder(m1)
  76. print("\n\nTree #2 is mirror of Tree #1 to check the correctness : ")
  77. print("TREE #1 : ")
  78. preorder(m1)
  79. print("\nTREE #2 : ")
  80. preorder(m2)
Add Comment
Please, Sign In to add comment