Maximum width of a binary tree | A binary tree node ; Function to get the maximum width of a binary tree ; Create an array that will store count of nodes at each level ; Fill the count array using preorder traversal ; Return the maximum value from count array ; A function that fills count array with count of nodes at every level of given binary tree ; Compute the " height " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node . ; compute the height of each subtree ; use the larger one ; Return the maximum value from count array ; Constructed bunary tree is : 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7
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 h = height ( root ) NEW_LINE count = [ 0 ] * h NEW_LINE level = 0 NEW_LINE getMaxWidthRecur ( root , count , level ) NEW_LINE return getMax ( count , h ) NEW_LINE DEDENT def getMaxWidthRecur ( root , count , level ) : NEW_LINE INDENT if root is not None : NEW_LINE INDENT count [ level ] += 1 NEW_LINE getMaxWidthRecur ( root . left , count , level + 1 ) NEW_LINE getMaxWidthRecur ( root . right , count , level + 1 ) NEW_LINE DEDENT DEDENT def height ( node ) : NEW_LINE INDENT if node is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT lHeight = height ( node . left ) NEW_LINE rHeight = height ( node . right ) NEW_LINE return ( lHeight + 1 ) if ( lHeight > rHeight ) else ( rHeight + 1 ) NEW_LINE DEDENT DEDENT def getMax ( count , n ) : NEW_LINE INDENT max = count [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( count [ i ] > max ) : NEW_LINE INDENT max = count [ i ] NEW_LINE DEDENT DEDENT return max 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