m2skills

width bt python

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