Sum of heights of all individual nodes in a binary tree | Compute the " maxHeight " of a particular Node ; compute the height of each subtree ; use the larger one ; Helper class that allocates a new Node with the given data and None left and right pointers . ; Function to sum of heights of individual Nodes Uses Inorder traversal ; Driver code
def getHeight ( Node ) : NEW_LINE INDENT if ( Node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT lHeight = getHeight ( Node . left ) NEW_LINE rHeight = getHeight ( Node . right ) NEW_LINE if ( lHeight > rHeight ) : NEW_LINE INDENT return ( lHeight + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( rHeight + 1 ) NEW_LINE DEDENT DEDENT DEDENT class newNode : 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 getTotalHeight ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( getTotalHeight ( root . left ) + getHeight ( root ) + getTotalHeight ( root . right ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE DEDENT print ( " Sum ▁ of ▁ heights ▁ of ▁ all ▁ Nodes ▁ = " , getTotalHeight ( root ) ) NEW_LINE