m2skills

vertical order bt python

Jun 22nd, 2018
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. # http://code2begin.blogspot.com
  2. # Program to print the nodes of the binary tree in vertical order using horizontal distance from the root node
  3.  
  4. # node class
  5. class node:
  6.     def __init__(self, element):
  7.         self.data = element
  8.         self.hd = -1
  9.         self.left = None
  10.         self.right = None
  11.  
  12.  
  13.  
  14. # function to print the nodes of the binary tree in vertical order
  15. # using horizontal distance of a node from the root node
  16. def vertical_order(root):
  17.     if root is None:
  18.         return
  19.  
  20.     # initialize a map and queue
  21.     # we will use iterative BFS traversal to solve this
  22.     M = dict()
  23.     Q = list()
  24.  
  25.     # push root in queue and initialize horizontal distance
  26.     Q.append(root)
  27.     horizontal_distance = root.hd
  28.  
  29.     while len(Q) > 0:
  30.         current = Q[0]
  31.         del Q[0]
  32.         if current.hd in M.keys():
  33.             M[current.hd].append(current.data)
  34.         else:
  35.             M[current.hd] = [current.data]
  36.  
  37.         # update horizontal distance of the left child and put it in the queue
  38.         if current.left is not None:
  39.             current.left.hd = current.hd - 1
  40.             Q.append(current.left)
  41.  
  42.         # update horizontal distance of the right child and put it in the queue
  43.         if current.right is not None:
  44.             current.right.hd = current.hd + 1
  45.             Q.append(current.right)
  46.  
  47.     # printing the contents of the map
  48.     for horizontal_distance, elements in zip(M.keys(), M.values()):
  49.         print("Nodes at " + str(horizontal_distance) + " : " + str(elements))
  50.  
  51.  
  52.  
  53. head = node(1)
  54. head.left = node(2)
  55. head.right = node(3)
  56. head.left.left = node(4)
  57. head.left.right = node(5)
  58. head.right.right = node(6)
  59. head.left.left.right = node(7)
  60. head.right.right.left = node(8)
  61. head.left.left.right.left = node(9)
  62. head.left.left.right.left.left = node(10)
  63. head.right.right.left.right = node(11)
  64. head.hd = 0
  65.  
  66. print("Vertical order traversal of the binary tree is : ")
  67. vertical_order(head)
Add Comment
Please, Sign In to add comment