2013-11-26 48 views
0

晚上好C中的二叉树:遍历指定级别

我有一个任务:计算树指定级别元素的平均值。我不知道如何在树中定义一个特定的水平,并得到节点的上这个级别的元素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; 
    } 

如果可能的话,建议我要的功能这个任务。

+1

这是C++,而不是C. –

+0

您是否知道您的教师在“指定级别”上的含义? –

+0

@qwrrty:我猜根节点级别0,它下面的两个子节点级别1等。 –

回答

1
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; 
    } 
}