Maximum width of a binary tree | A binary tree node ; Function to get the maximum width of a binary tree ; base case ; Initialize result ; Do Level order traversal keeping track of number of nodes at every level ; Get the size of queue when the level order traversal for one level finishes ; Update the maximum node count value ; Iterate for all the nodes in the queue currently ; Dequeue an node from queue ;  ; Driver program to test above function ; Function call
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getMaxWidth ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT maxWidth = 0 NEW_LINE q = [ ] NEW_LINE q . insert ( 0 , root ) NEW_LINE while ( q != [ ] ) : NEW_LINE INDENT count = len ( q ) NEW_LINE maxWidth = max ( count , maxWidth ) NEW_LINE while ( count is not 0 ) : NEW_LINE INDENT count = count - 1 NEW_LINE temp = q [ - 1 ] NEW_LINE q . pop ( ) NEW_LINE if temp . left is not None : NEW_LINE INDENT q . insert ( 0 , temp . left ) NEW_LINE DEDENT if temp . right is not None : NEW_LINE INDENT q . insert ( 0 , temp . right ) NEW_LINE DEDENT DEDENT DEDENT return maxWidth NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . right = Node ( 8 ) NEW_LINE root . right . right . left = Node ( 6 ) NEW_LINE root . right . right . right = Node ( 7 ) NEW_LINE print " Maximum ▁ width ▁ is ▁ % d " % ( getMaxWidth ( root ) ) NEW_LINE