Reputation: 2500
Good evening
I have a task: Calculate an average value of the elements of the tree specified level. I have no idea how to define a particular level in tree and get summ of node's elements on this level...
Here is the existing code:
#include <iostream>
#include <conio.h>
using namespace std;
struct Node
{
int x;
Node *left, *right;
};
Node *tree = NULL;
void push( int a, Node**Mytree)
{
if( (*Mytree) == NULL ){
(*Mytree) = new Node;
(*Mytree) -> x = a;
(*Mytree) -> left = (*Mytree) -> right = NULL;
return;
}
if( a > ( (*Mytree) -> x) ) push( a, &(*Mytree) -> right);
else push( a, &(*Mytree) -> left);
}
void print (Node *Mytree, int u)
{
if(Mytree){
print(Mytree->left, u+1);
for ( int i = 0; i < u; i++) cout << " ";
cout << Mytree -> x<< endl;
print( Mytree -> right, u+1);
}
}
int main()
{
int n,s;
cout << "Enter amount of elements: \n";
cin >> n;
for ( int i =0; i < n; ++i){
cout << "Enter element's value: \n";
cin >> s;
push ( s , &tree);
}
cout << "Printing your tree...\n";
print(tree,0);
getch();
return 0;
}
If it possible, suggest me a function for this task.
Upvotes: 0
Views: 63
Reputation: 6984
struct result {
int sum;
unsigned int cnt;
}
void count_elems(struct Node const *tree, unsigned int lvl, struct result *res)
{
if (!tree) {
; /* noop */
} else if (lvl > 0) {
count_elems(tree->left, lvl - 1, res);
count_elems(tree->right, lvl - 1, res);
} else {
res->sum += tree->x;
++res->cnt;
}
}
Upvotes: 1