Given a positive integer L which represents the number of levels in a perfect binary tree. Given that the leaf nodes in this perfect binary tree are numbered starting from 1 to n, where n is the number of leaf nodes. And the parent node is the sum of the two child nodes. Our task is to write a program to print the sum of all of the nodes of this perfect binary tree.
Examples:
Input : L = 3
Output : 30
Explanation : Tree will be - 10
/ \
3 7
/ \ / \
1 2 3 4
Input : L = 2
Output : 6
Explanation : Tree will be - 3
/ \
1 2
Naive Approach: The simplest solution is to first generate the value of all of the nodes of the perfect binary tree and then calculate the sum of all of the nodes. We can first generate all of the leaf nodes and then proceed in the bottom-up fashion to generate rest of the nodes. We know that in a perfect binary tree, the number of leaf nodes can be given by 2L-1, where L is the number of levels. The number of nodes in a perfect binary tree as we move upward from the bottom will get decreased by half.
Below is the implementation of above idea:
C++
#include <bits/stdc++.h>
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;
}
|
Java
import java.util.*;
class GFG
{
static int sumNodes( int l)
{
int leafNodeCount = ( int )Math.pow( 2 , l - 1 );
Vector<Vector
<Integer>> vec = new Vector<Vector
<Integer>>();
for ( int i = 1 ; i <= l; i++)
vec.add( new Vector<Integer>());
for ( int i = 1 ;
i <= leafNodeCount; i++)
vec.get(l - 1 ).add(i);
for ( int i = l - 2 ; i >= 0 ; i--)
{
int k = 0 ;
while (k < vec.get(i + 1 ).size() - 1 )
{
vec.get(i).add(vec.get(i + 1 ).get(k) +
vec.get(i + 1 ).get(k + 1 ));
k += 2 ;
}
}
int sum = 0 ;
for ( int i = 0 ; i < l; i++)
{
for ( int j = 0 ;
j < vec.get(i).size(); j++)
sum += vec.get(i).get(j);
}
return sum;
}
public static void main(String args[])
{
int l = 3 ;
System.out.println(sumNodes(l));
}
}
|
Python3
def SumNodes(l):
leafNodeCount = pow ( 2 , l - 1 )
vec = [[] for i in range (l)]
for i in range ( 1 , leafNodeCount + 1 ):
vec[l - 1 ].append(i)
for i in range (l - 2 , - 1 , - 1 ):
k = 0
while (k < len (vec[i + 1 ]) - 1 ):
vec[i].append(vec[i + 1 ][k] +
vec[i + 1 ][k + 1 ])
k + = 2
Sum = 0
for i in range (l):
for j in range ( len (vec[i])):
Sum + = vec[i][j]
return Sum
if __name__ = = '__main__' :
l = 3
print (SumNodes(l))
|
C#
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));
}
}
|
Javascript
<script>
function sumNodes(l)
{
let leafNodeCount = Math.pow(2, l - 1);
let vec = [];
for (let i = 1; i <= l; i++)
{
vec.push([]);
}
for (let i = 1; i <= leafNodeCount; i++)
{
vec[l - 1].push(i);
}
for (let i = l - 2; i >= 0; i--)
{
let k = 0;
while (k < vec[i + 1].length - 1)
{
vec[i].push(vec[i + 1][k] + vec[i + 1][k + 1]);
k += 2;
}
}
let sum = 0;
for (let i = 0; i < l; i++)
{
for (let j = 0; j < vec[i].length; j++)
{
sum += vec[i][j];
}
}
return sum;
}
let l = 3;
document.write(sumNodes(l));
</script>
|
Time Complexity: O(n), where n is the total number of nodes in the perfect binary tree.
Auxiliary Space: O(l)
Efficient Approach: An efficient approach is to observe that we only need to find the sum of all of the nodes. We can easily get the sum of all nodes at the last level using the formula of sum of first n natural numbers. Also, it can be seen that, as it is a perfect binary tree and parent nodes will be the sum of children nodes so the sum of nodes at all of the levels will be same. Therefore, we just need to find the sum of nodes at last level and multiply it by the total number of levels.
Below is the implementation of above idea:
C++
#include <bits/stdc++.h>
using namespace std;
int sumNodes( int l)
{
int leafNodeCount = pow (2, l - 1);
int sumLastLevel = 0;
sumLastLevel = (leafNodeCount * (leafNodeCount + 1)) / 2;
int sum = sumLastLevel * l;
return sum;
}
int main()
{
int l = 3;
cout << sumNodes(l);
return 0;
}
|
Java
import java.io.*;
import java.lang.Math;
class GFG {
static double sumNodes( int l)
{
double leafNodeCount = Math.pow( 2 , l - 1 );
double sumLastLevel = 0 ;
sumLastLevel = (leafNodeCount *
(leafNodeCount + 1 )) / 2 ;
double sum = sumLastLevel * l;
return sum;
}
public static void main (String[] args) {
int l = 3 ;
System.out.println(sumNodes(l));
}
}
|
Python3
import math
def sumNodes(l):
leafNodeCount = math. pow ( 2 , l - 1 );
sumLastLevel = 0 ;
sumLastLevel = ((leafNodeCount *
(leafNodeCount + 1 )) / 2 );
sum = sumLastLevel * l;
return int ( sum );
l = 3 ;
print (sumNodes(l));
|
C#
using System;
using System.Collections.Generic;
class GFG {
static double sumNodes( int l)
{
double leafNodeCount = Math.Pow(2, l - 1);
double sumLastLevel = 0;
sumLastLevel = (leafNodeCount *
(leafNodeCount + 1)) / 2;
double sum = sumLastLevel * l;
return sum;
}
public static void Main()
{
int l = 3;
Console.Write(sumNodes(l));
}
}
|
PHP
<?php
function sumNodes( $l )
{
$leafNodeCount = ( $l - 1) *
( $l - 1);
$sumLastLevel = 0;
$sumLastLevel = ( $leafNodeCount *
( $leafNodeCount + 1)) / 2;
$sum = $sumLastLevel * $l ;
return $sum ;
}
$l = 3;
echo (sumNodes( $l ));
?>
|
Javascript
<script>
function sumNodes(l)
{
let leafNodeCount = Math.pow(2, l - 1);
let sumLastLevel = 0;
sumLastLevel = (leafNodeCount * (leafNodeCount + 1)) / 2;
let sum = sumLastLevel * l;
return sum;
}
let l = 3;
document.write(sumNodes(l));
</script>
|
Time Complexity: O(log(L)), due to pow()
Auxiliary Space: O(1)