I have a binary tree. It is NOT a binary search tree. I's just a simple binary tree. Each node has an integer value, and 2 links- left and right. What I must do is to write a function that will calculate the average of the node values.
Please make some effort to help me, it's very important. Any codes, ideas, anything may be truly helpful. Thanks.
What is the exact structure of your binary tree? Is it just a simple structure containing a node named left and a node named right? If so, you could write a function comparable to this:
1 2 3 4 5 6 7
int getAverage(Node* root)
{
int sum = 0; // The sum
int elements = 0; // The number of elements
sum = getSum(root,elements); //Calculate the sum of all elements, and return the number of elements
return sum / elements;
}
The getSum function could easily be implemented as a recursive function:
1 2 3 4 5 6 7 8 9 10
int getSum(Node* root, int& elements)
{
++elements; // Increase the number of elements
int sum = root->value; // Get the value of this element
if(root->left != NULL)
sum += getSum(root->left,elements); // Calculate the sum of the left tree side
if(root->right != NULL)
sum += getSum(root->right, elements); // Calculate the sum of the right tree side
return sum; // Return the result
}
Of course, this could be rewritten into a single function using a simple loop. Note that I did not test this code yet, that's up to you.