Maximum width of a binary tree | A binary tree node ; Function to get the maximum width of a binary tree ; Get width of each level and compare the width with maximum width so far ; Get width of a given level ; 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 ; Constructed binary tree is : 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 ; 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 maxWidth = 0 NEW_LINE h = height ( root ) NEW_LINE for i in range ( 1 , h + 1 ) : NEW_LINE INDENT width = getWidth ( root , i ) NEW_LINE if ( width > maxWidth ) : NEW_LINE INDENT maxWidth = width NEW_LINE DEDENT DEDENT return maxWidth NEW_LINE DEDENT def getWidth ( root , level ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if level == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif level > 1 : NEW_LINE INDENT return ( getWidth ( root . left , level - 1 ) + getWidth ( root . right , 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 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