Write a program to find Average of Nodes in tree

To find average , calculate the sum of all node by traversing whole tree and divide it by number of node it contains .

Code :

void average(Node n, int sumcount[]) {
  if (n == null) 
  sumcount[0] += n.data;  // Store the sum of data
  sumcount[1] += 1;       // Store the count of node .
  average(n.left, sumcount);	
  average(n.right, sumcount);

Average will be sumcount[0]/sumcount[1]

Time & Space Complexities: Since this program is similar to traversal of tree, time and space complexities will be same as Tree traversal .

Leave a Reply

Your email address will not be published. Required fields are marked *

For Inserting code :
Paste your code in the comment form, select it and then click the language link

C | C++ | Java |