- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Find sum of all nodes of the given perfect binary tree in C++

Suppose we have a positive integer L, which represents the number of levels in a perfect binary tree. The leaf nodes in this perfect binary tree are numbered starting from 1 to n. Where the n is number of leaf nodes. The parent node is the sum of children. Our task is to write a program to print the sum of all of the nodes of this perfect binary tree. So if the tree is like below −

So total sum is 30.

If we see closer, we need to find the sum of all of the nodes. As the leaf nodes are holding values from 1 to n, then we can use the formula n(n+1)/2 to get sum of leaf nodes. As this is perfect binary tree, the sum of each levels will be same. So find the sum of last level, then multiply it with number of levels.

## Example

#include<iostream> #include<cmath> using namespace std; int treeSum(int level) { int total_leaves = pow(2, level - 1); int leaf_sum = 0; leaf_sum = (total_leaves * (total_leaves + 1)) / 2; int sum = leaf_sum * level; return sum; } int main() { int levels = 4; cout << "Sum of all nodes for a perfect binary tree with level " << levels << " is: " << treeSum(levels); }

## Output

Sum of all nodes for a perfect binary tree with level 4 is: 144

- Related Questions & Answers
- Find the sum of left leaf nodes of a given Binary Tree in C++
- Maximum sum of non-leaf nodes among all levels of the given binary tree in C++
- Python Program to Find the Sum of All Nodes in a Binary Tree
- Find sum of all right leaves in a given Binary Tree in C++
- Find sum of all left leaves in a given Binary Tree in C++
- Product of all leaf nodes of binary tree in C++
- Product of all nodes in a Binary Tree in C++
- Print all odd nodes of Binary Search Tree in C++
- Print all internal nodes of a Binary tree in C++
- Print all even nodes of Binary Search Tree in C++
- Python Program to Find the Sum of all Nodes in a Tree
- Find the largest Perfect Subtree in a given Binary Tree in Python
- Find maximum among all right nodes in Binary Tree in C++
- Print all nodes between two given levels in Binary Tree in C++
- XOR of all the nodes in the sub-tree of the given node in C++

Advertisements