m2skills

right view iter python

Jul 24th, 2018
810
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. # http://code2begin.blogspot.com
  2. # Program to Right view of the binary tree iteratively
  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. # BFS itertative using queue for right view
  12. def right_view_iterative(root):
  13.     if root is None:
  14.         return
  15.  
  16.     # creating a Queue for storing node for level wise traversal
  17.     Q = list()
  18.     Q.append(root)
  19.     level = 0
  20.     max_level = 0
  21.     print("Right view of the binary tree is : ")
  22.     while len(Q):
  23.         # store the current size of the Q
  24.         count = len(Q)
  25.         level += 1
  26.         while count != 0:
  27.             # pop the first node from the queue
  28.             NODE = Q[0]
  29.             del Q[0]
  30.             if level > max_level:
  31.                 print(NODE.data, end=" ")
  32.                 max_level = level
  33.  
  34.             # push the right child on queue
  35.             if NODE.right is not None:
  36.                 Q.append(NODE.right)
  37.                
  38.             # push the left child on queue
  39.             if NODE.left is not None:
  40.                 Q.append(NODE.left)
  41.             count -= 1
  42.     print()
  43.  
  44. head = node(1)
  45. head.left = node(2)
  46. head.right = node(3)
  47. head.left.left = node(4)
  48. head.left.right = node(5)
  49. head.right.right = node(6)
  50. head.left.left.right = node(7)
  51. head.right.right.left = node(8)
  52. head.left.left.right.left = node(9)
  53. head.left.left.right.left.left = node(10)
  54. head.right.right.left.right = node(11)
  55. right_view_iterative(head)
Add Comment
Please, Sign In to add comment