m2skills

spiral BT python

Jun 3rd, 2018
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. # http://code2begin.blogspot.com
  2. # Program to print nodes of tree using spiral order traversal
  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 tree using spiral level wise traversal
  12. def spiral_traversal(root):
  13.     if root is None:
  14.         return
  15.  
  16.     STACK1 = list()
  17.     STACK2 = list()
  18.     level = 1
  19.     STACK1.append(root)
  20.     while len(STACK1) > 0 or len(STACK2) > 0:
  21.         print("\nNodes at level " + str(level) + " are : ")
  22.         level += 1
  23.         while len(STACK1) > 0:
  24.             # pop the first node from the queue
  25.             NODE = STACK1[0]
  26.             del STACK1[0]
  27.             print(NODE.data, end=" ")
  28.  
  29.             # push the left child on queue
  30.             if NODE.right is not None:
  31.                 STACK2.append(NODE.right)
  32.  
  33.             # push the right child on queue
  34.             if NODE.left is not None:
  35.                 STACK2.append(NODE.left)
  36.  
  37.         print("\nNodes at level " + str(level) + " are : ")
  38.         level += 1
  39.         while len(STACK2) > 0:
  40.             # pop the first node from the queue
  41.             NODE = STACK2[0]
  42.             del STACK2[0]
  43.             print(NODE.data, end=" ")
  44.  
  45.             # push the left child on queue
  46.             if NODE.right is not None:
  47.                 STACK1.append(NODE.right)
  48.  
  49.             # push the right child on queue
  50.             if NODE.left is not None:
  51.                 STACK1.append(NODE.left)
  52.  
  53.  
  54.  
  55. head = node(1)
  56. head.left = node(2)
  57. head.right = node(3)
  58. head.left.left = node(4)
  59. head.left.right = node(5)
  60. head.right.right = node(6)
  61. head.left.left.right = node(7)
  62. head.right.right.left = node(8)
  63. head.left.left.right.left = node(9)
  64. head.left.left.right.left.left = node(10)
  65. head.right.right.left.right = node(11)
  66. print("\n\nSPIRAL Level wise traversal of the above binary tree is : ")
  67. spiral_traversal(head)
Add Comment
Please, Sign In to add comment