Python program to find sum of all nodes of the given perfect binary tree.
Description: To find the sum of the all nodes of the perfect binary tree, we need to find the sum of all of the nodes.By using the formula of sum of first n natural number we can get easily the sum of all nodes at last level.As we know in perfect binary tree,parent node will be the sum of children node, so sum of the nodes at all of the levels will be the same.So we just need to find the sum of nodes at last level and multiply it by the total number of levels.
Program :
# function to find sum of all of the nodes of given perfect binary tree import math
defsumOfNodes(levl):# no of leaf nodes
countOfLeafNodes = math.pow(2, levl - 1);
lastLevelSum = 0;
# sum of nodes at last level
sumAtLastLevel = ((countOfLeafNodes *
(countOfLeafNodes + 1)) / 2);
# sum of all nodes
sum = sumAtLastLevel * levl;
return int(sum);
# Driver Code
levl= 4;
print (sumOfNodes(levl));
Comments