0
我有一个任务:计算树指定级别元素的平均值。我不知道如何在树中定义一个特定的水平,并得到节点的上这个级别的元素SUMM ...
这里是现有代码:
#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;
}
如果可能的话,建议我要的功能这个任务。
这是C++,而不是C. –
您是否知道您的教师在“指定级别”上的含义? –
@qwrrty:我猜根节点级别0,它下面的两个子节点级别1等。 –