- 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++
- 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++
- Find the largest Perfect Subtree in a given Binary Tree in Python
- XOR of all the nodes in the sub-tree of the given node in C++
- Find maximum among all right nodes in Binary Tree in C++
- Print all nodes between two given levels in Binary Tree in C++
- Find distance between two nodes of a Binary Tree in C++
- Print Levels of all nodes in a Binary Tree in C++ Programming.
- All Nodes Distance K in Binary Tree in C++
- Find distance between two nodes of a Binary Tree in C++ Program

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

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.

#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); }

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

Advertisements