Find sum of all nodes of the given perfect binary tree | function to find Sum of all of the nodes of given perfect binary tree ; no of leaf nodes ; list of vector to store nodes of all of the levels ; store the nodes of last level i . e . , the leaf nodes ; store nodes of rest of the level by moving in bottom - up manner ; loop to calculate values of parent nodes from the children nodes of lower level ; store the value of parent node as Sum of children nodes ; traverse the list of vector and calculate the Sum ; Driver Code
def SumNodes ( l ) : NEW_LINE INDENT leafNodeCount = pow ( 2 , l - 1 ) NEW_LINE vec = [ [ ] for i in range ( l ) ] NEW_LINE for i in range ( 1 , leafNodeCount + 1 ) : NEW_LINE INDENT vec [ l - 1 ] . append ( i ) NEW_LINE DEDENT for i in range ( l - 2 , - 1 , - 1 ) : NEW_LINE INDENT k = 0 NEW_LINE while ( k < len ( vec [ i + 1 ] ) - 1 ) : NEW_LINE INDENT vec [ i ] . append ( vec [ i + 1 ] [ k ] + vec [ i + 1 ] [ k + 1 ] ) NEW_LINE k += 2 NEW_LINE DEDENT DEDENT Sum = 0 NEW_LINE for i in range ( l ) : NEW_LINE INDENT for j in range ( len ( vec [ i ] ) ) : NEW_LINE INDENT Sum += vec [ i ] [ j ] NEW_LINE DEDENT DEDENT return Sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT l = 3 NEW_LINE print ( SumNodes ( l ) ) NEW_LINE DEDENT