m2skills

top view python

Jun 1st, 2018
786
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. # http://code2begin.blogspot.com
  2. # Program to print the top view of the binary tree
  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 top view of the binary tree
  13. def top_view(root):
  14.     if root is None:
  15.         return
  16.  
  17.     # we keep track of the horizontal distance of the node from the root node
  18.     # to print the bottom view
  19.     # hd = horizontal distance from the root node
  20.     # creating a Queue for storing node for level wise traversal
  21.     # and a map for mapping horizontal distances with the node data
  22.     Q = []
  23.     Map = dict()
  24.  
  25.     Q.append(root)
  26.     while len(Q) > 0:
  27.  
  28.         # pop the first node from the queue
  29.         p = Q[0]
  30.         del Q[0]
  31.  
  32.         hd = p.hd
  33.  
  34.         # if a horizontal distance is already mapped with a value then
  35.         # we don't replace it with a new value
  36.         if hd not in Map.keys():
  37.             Map[hd] = p.data
  38.  
  39.         # increase the horizontal distance from the root node in negative direction
  40.         # and push the node on queue
  41.         if p.left is not None:
  42.             p.left.hd = hd - 1
  43.             Q.append(p.left)
  44.  
  45.         # increase the horizontal distance from the root node in positive direction
  46.         # and push the node on queue
  47.         if p.right is not None:
  48.             p.right.hd = hd + 1
  49.             Q.append(p.right)
  50.  
  51.     # print the generated map
  52.     print("Top view of the binary tree is : ")
  53.     print(list(Map.values()))
  54.  
  55.  
  56.  
  57. head = node(1)
  58. head.left = node(2)
  59. head.right = node(3)
  60. head.left.left = node(4)
  61. head.left.right = node(5)
  62. head.right.right = node(6)
  63. head.left.left.right = node(7)
  64. head.right.right.left = node(8)
  65. head.left.left.right.left = node(9)
  66. head.left.left.right.left.left = node(10)
  67. head.right.right.left.right = node(11)
  68. head.hd = 0
  69. top_view(head)
Add Comment
Please, Sign In to add comment