Find sum of all nodes of the given perfect binary tree | C # program to implement the above approach ; 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 ; initialize ; 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
using System ; using System . Collections . Generic ; public class GFG { public static int sumNodes ( int l ) { int leafNodeCount = ( int ) Math . Pow ( 2 , l - 1 ) ; List < List < int > > vec = new List < List < int > > ( ) ; for ( int i = 1 ; i <= l ; i ++ ) { vec . Add ( new List < int > ( ) ) ; } for ( int i = 1 ; i <= leafNodeCount ; i ++ ) { vec [ l - 1 ] . Add ( i ) ; } for ( int i = l - 2 ; i >= 0 ; i -- ) { int k = 0 ; while ( k < vec [ i + 1 ] . Count - 1 ) { vec [ i ] . Add ( 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 ] . Count ; j ++ ) { sum += vec [ i ] [ j ] ; } } return sum ; } public static void Main ( string [ ] args ) { int l = 3 ; Console . WriteLine ( sumNodes ( l ) ) ; } }