Find sum of all nodes of the given perfect binary tree
Last Updated :
26 Dec, 2022
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;
// function to find sum of all of the nodes
// of given perfect binary tree
int sumNodes(int l)
{
// no of leaf nodes
int leafNodeCount = pow(2, l - 1);
// list of vector to store nodes of
// all of the levels
vector<int> vec[l];
// store the nodes of last level
// i.e., the leaf nodes
for (int i = 1; i <= leafNodeCount; i++)
vec[l - 1].push_back(i);
// store nodes of rest of the level
// by moving in bottom-up manner
for (int i = l - 2; i >= 0; i--) {
int k = 0;
// loop to calculate values of parent nodes
// from the children nodes of lower level
while (k < vec[i + 1].size() - 1) {
// store the value of parent node as
// sum of children nodes
vec[i].push_back(vec[i + 1][k] +
vec[i + 1][k + 1]);
k += 2;
}
}
int sum = 0;
// traverse the list of vector
// and calculate the sum
for (int i = 0; i < l; i++) {
for (int j = 0; j < vec[i].size(); j++)
sum += vec[i][j];
}
return sum;
}
// Driver Code
int main()
{
int l = 3;
cout << sumNodes(l);
return 0;
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG
{
// function to find sum of
// all of the nodes of given
// perfect binary tree
static int sumNodes(int l)
{
// no of leaf nodes
int leafNodeCount = (int)Math.pow(2, l - 1);
// list of vector to store
// nodes of all of the levels
Vector<Vector
<Integer>> vec = new Vector<Vector
<Integer>>();
//initialize
for (int i = 1; i <= l; i++)
vec.add(new Vector<Integer>());
// store the nodes of last level
// i.e., the leaf nodes
for (int i = 1;
i <= leafNodeCount; i++)
vec.get(l - 1).add(i);
// store nodes of rest of
// the level by moving in
// bottom-up manner
for (int i = l - 2; i >= 0; i--)
{
int k = 0;
// loop to calculate values
// of parent nodes from the
// children nodes of lower level
while (k < vec.get(i + 1).size() - 1)
{
// store the value of parent
// node as sum of children nodes
vec.get(i).add(vec.get(i + 1).get(k) +
vec.get(i + 1).get(k + 1));
k += 2;
}
}
int sum = 0;
// traverse the list of vector
// and calculate the sum
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;
}
// Driver Code
public static void main(String args[])
{
int l = 3;
System.out.println(sumNodes(l));
}
}
// This code is contributed
// by Arnab Kundu
Python3
# Python3 program to implement the
# above approach
# function to find Sum of all of the
# nodes of given perfect binary tree
def SumNodes(l):
# no of leaf nodes
leafNodeCount = pow(2, l - 1)
# list of vector to store nodes of
# all of the levels
vec = [[] for i in range(l)]
# store the nodes of last level
# i.e., the leaf nodes
for i in range(1, leafNodeCount + 1):
vec[l - 1].append(i)
# store nodes of rest of the level
# by moving in bottom-up manner
for i in range(l - 2, -1, -1):
k = 0
# loop to calculate values of parent nodes
# from the children nodes of lower level
while (k < len(vec[i + 1]) - 1):
# store the value of parent node as
# Sum of children nodes
vec[i].append(vec[i + 1][k] +
vec[i + 1][k + 1])
k += 2
Sum = 0
# traverse the list of vector
# and calculate the Sum
for i in range(l):
for j in range(len(vec[i])):
Sum += vec[i][j]
return Sum
# Driver Code
if __name__ == '__main__':
l = 3
print(SumNodes(l))
# This code is contributed by PranchalK
C#
using System;
using System.Collections.Generic;
// C# program to implement
// the above approach
public class GFG
{
// function to find sum of
// all of the nodes of given
// perfect binary tree
public static int sumNodes(int l)
{
// no of leaf nodes
int leafNodeCount = (int)Math.Pow(2, l - 1);
// list of vector to store
// nodes of all of the levels
List<List<int>> vec = new List<List<int>>();
//initialize
for (int i = 1; i <= l; i++)
{
vec.Add(new List<int>());
}
// store the nodes of last level
// i.e., the leaf nodes
for (int i = 1; i <= leafNodeCount; i++)
{
vec[l - 1].Add(i);
}
// store nodes of rest of
// the level by moving in
// bottom-up manner
for (int i = l - 2; i >= 0; i--)
{
int k = 0;
// loop to calculate values
// of parent nodes from the
// children nodes of lower level
while (k < vec[i + 1].Count - 1)
{
// store the value of parent
// node as sum of children nodes
vec[i].Add(vec[i + 1][k] + vec[i + 1][k + 1]);
k += 2;
}
}
int sum = 0;
// traverse the list of vector
// and calculate the sum
for (int i = 0; i < l; i++)
{
for (int j = 0; j < vec[i].Count; j++)
{
sum += vec[i][j];
}
}
return sum;
}
// Driver Code
public static void Main(string[] args)
{
int l = 3;
Console.WriteLine(sumNodes(l));
}
}
// This code is contributed by Shrikant13
JavaScript
<script>
// Javascript program to implement the above approach
// function to find sum of
// all of the nodes of given
// perfect binary tree
function sumNodes(l)
{
// no of leaf nodes
let leafNodeCount = Math.pow(2, l - 1);
// list of vector to store
// nodes of all of the levels
let vec = [];
//initialize
for (let i = 1; i <= l; i++)
{
vec.push([]);
}
// store the nodes of last level
// i.e., the leaf nodes
for (let i = 1; i <= leafNodeCount; i++)
{
vec[l - 1].push(i);
}
// store nodes of rest of
// the level by moving in
// bottom-up manner
for (let i = l - 2; i >= 0; i--)
{
let k = 0;
// loop to calculate values
// of parent nodes from the
// children nodes of lower level
while (k < vec[i + 1].length - 1)
{
// store the value of parent
// node as sum of children nodes
vec[i].push(vec[i + 1][k] + vec[i + 1][k + 1]);
k += 2;
}
}
let sum = 0;
// traverse the list of vector
// and calculate the sum
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));
// This code is contributed by mukesh07.
</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;
// function to find sum of all of the nodes
// of given perfect binary tree
int sumNodes(int l)
{
// no of leaf nodes
int leafNodeCount = pow(2, l - 1);
int sumLastLevel = 0;
// sum of nodes at last level
sumLastLevel = (leafNodeCount * (leafNodeCount + 1)) / 2;
// sum of all nodes
int sum = sumLastLevel * l;
return sum;
}
// Driver Code
int main()
{
int l = 3;
cout << sumNodes(l);
return 0;
}
Java
// Java code to find sum of all nodes
// of the given perfect binary tree
import java.io.*;
import java.lang.Math;
class GFG {
// function to find sum of
// all of the nodes of given
// perfect binary tree
static double sumNodes(int l)
{
// no of leaf nodes
double leafNodeCount = Math.pow(2, l - 1);
double sumLastLevel = 0;
// sum of nodes at last level
sumLastLevel = (leafNodeCount *
(leafNodeCount + 1)) / 2;
// sum of all nodes
double sum = sumLastLevel * l;
return sum;
}
// Driver Code
public static void main (String[] args) {
int l = 3;
System.out.println(sumNodes(l));
}
}
// This code is contributed by
// Anuj_{AJ_67}
Python3
# function to find sum of all of the nodes
# of given perfect binary tree
import math
def sumNodes(l):
# no of leaf nodes
leafNodeCount = math.pow(2, l - 1);
sumLastLevel = 0;
# sum of nodes at last level
sumLastLevel = ((leafNodeCount *
(leafNodeCount + 1)) / 2);
# sum of all nodes
sum = sumLastLevel * l;
return int(sum);
# Driver Code
l = 3;
print (sumNodes(l));
# This code is contributed by manishshaw
C#
// C# code to find sum of all nodes
// of the given perfect binary tree
using System;
using System.Collections.Generic;
class GFG {
// function to find sum of
// all of the nodes of given
// perfect binary tree
static double sumNodes(int l)
{
// no of leaf nodes
double leafNodeCount = Math.Pow(2, l - 1);
double sumLastLevel = 0;
// sum of nodes at last level
sumLastLevel = (leafNodeCount *
(leafNodeCount + 1)) / 2;
// sum of all nodes
double sum = sumLastLevel * l;
return sum;
}
// Driver Code
public static void Main()
{
int l = 3;
Console.Write(sumNodes(l));
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
PHP
<?php
// PHP code to 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
function sumNodes($l)
{
// no of leaf nodes
$leafNodeCount = ($l - 1) *
($l - 1);
$sumLastLevel = 0;
// sum of nodes at last level
$sumLastLevel = ($leafNodeCount *
($leafNodeCount + 1)) / 2;
// sum of all nodes
$sum = $sumLastLevel * $l;
return $sum;
}
// Driver Code
$l = 3;
echo (sumNodes($l));
// This code is contributed by
// Manish Shaw (manishshaw1)
?>
JavaScript
<script>
// Javascript code to 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
function sumNodes(l)
{
// no of leaf nodes
let leafNodeCount = Math.pow(2, l - 1);
let sumLastLevel = 0;
// sum of nodes at last level
sumLastLevel = (leafNodeCount * (leafNodeCount + 1)) / 2;
// sum of all nodes
let sum = sumLastLevel * l;
return sum;
}
let l = 3;
document.write(sumNodes(l));
// This code is contributed by divyeshrabadiya07.
</script>
Time Complexity: O(log(L)), due to pow()
Auxiliary Space: O(1)
Similar Reads
Find the largest Perfect Subtree in a given Binary Tree
Given a Binary Tree, the task is to find the size of largest Perfect sub-tree in the given Binary Tree. Perfect Binary Tree - A Binary tree is Perfect Binary Tree in which all internal nodes have two children and all leaves are at the same level. Examples: Input: 1 / \ 2 3 / \ / 4 5 6 Output: Size :
12 min read
Sum of all the Boundary Nodes of a Binary Tree
Given a binary tree, the task is to print the sum of all the boundary nodes of the tree. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 28 Input: 1 / \ 2 3 \ / 4 5 \ 6 / \ 7 8 Output: 36 Approach: We have already discussed the Boundary Traversal of a Binary tree. Here we will find the sum of the
10 min read
Find sum of all left leaves in a given Binary Tree
Given a Binary Tree, find the sum of all left leaves in it. For example, sum of all left leaves in below Binary Tree is 5+1=6. Recommended PracticeSum of Left Leaf NodesTry It! The idea is to traverse the tree, starting from root. For every node, check if its left subtree is a leaf. If it is, then a
15+ min read
Sum of all leaf nodes of binary tree
Given a binary tree, find the sum of all the leaf nodes.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Output : Sum = 4 + 5 + 8 + 7 = 24 Recommended PracticeSum of Leaf NodesTry It! The idea is to traverse the tree in any fashion and check if the node is the leaf node or not. If the node is the lea
5 min read
Print all even nodes of Binary Search Tree
Given a binary search tree. The task is to print all even nodes of the binary search tree. Examples: Input : 5 / \ 3 7 / \ / \ 2 4 6 8 Output : 2 4 6 8 Input : 14 / \ 12 17 / \ / \ 8 13 16 19 Output : 8 12 14 16 Approach: Traverse the Binary Search tree and check if current node's value is even. If
8 min read
Sum of all the child nodes with even parent values in a Binary Tree
Given a binary tree, the task is to find the sum of all the nodes whose parent is even.Examples: Input: 1 / \ 3 8 / \ 5 6 / 1Output: 11The only even nodes are 8 and 6 and the sum of their children is 5 + 6 = 11.Input: 2 / \ 3 8 / / \ 2 5 6 / \ 1 3Output: 253 + 8 + 5 + 6 + 3 = 25Approach: Initialise
14 min read
Product of all leaf nodes of binary tree
Given a binary tree, find the product of all the leaf nodes. Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Output : product = 4 * 5 * 8 * 7 = 1120 The idea is to traverse the tree in any fashion and check if the node is the leaf node or not. If the node is the leaf node, multiply node data to a va
5 min read
Sum of all nodes in a binary tree
Give an algorithm for finding the sum of all elements in a binary tree. In the above binary tree sum = 106. Recommended PracticeSum of Binary TreeTry It!The idea is to recursively, call left subtree sum, right subtree sum and add their values to current node's data. Implementation: C++ /* Program to
15+ min read
Print Levels of all nodes in a Binary Tree
Given a Binary Tree and a key, write a function that prints levels of all keys in given binary tree. For example, consider the following tree. If the input key is 3, then your function should return 1. If the input key is 4, then your function should return 3. And for key which is not present in key
7 min read
Sum of specially balanced nodes from a given Binary Tree
Given a Binary Tree, the task is to find the sum of all the specially balanced nodes in the given Binary Tree. A specially balanced node in a Binary Tree contains the sum of nodes of one subtree(either left or right) as even and the sum of the other subtree as odd.The nodes having only one child or
13 min read