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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumNodes ( int l ) { int leafNodeCount = pow ( 2 , l - 1 ) ; vector < int > vec [ l ] ; for ( int i = 1 ; i <= leafNodeCount ; i ++ ) vec [ l - 1 ] . push_back ( i ) ; for ( int i = l - 2 ; i >= 0 ; i -- ) { int k = 0 ; while ( k < vec [ i + 1 ] . size ( ) - 1 ) { vec [ i ] . push_back ( vec [ i + 1 ] [ k ] + vec [ i + 1 ] [ k + 1 ] ) ; k += 2 ; } } int sum = 0 ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = 0 ; j < vec [ i ] . size ( ) ; j ++ ) sum += vec [ i ] [ j ] ; } return sum ; } int main ( ) { int l = 3 ; cout << sumNodes ( l ) ; return 0 ; }