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

C中的二叉树:遍历指定级别,c,binary-tree,C,Binary Tree,晚上好 我有一个任务:计算指定级别的树元素的平均值。我不知道如何在树中定义一个特定的级别,并在这个级别上获取节点元素的总和 以下是现行守则: #include <iostream> #include <conio.h> using namespace std; struct Node { int x; Node *left, *right; }; Node *tree = NULL; void push( int a, Node**My

晚上好

我有一个任务:计算指定级别的树元素的平均值。我不知道如何在树中定义一个特定的级别,并在这个级别上获取节点元素的总和

以下是现行守则:

#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;
     }
#包括
#包括
使用名称空间std;
结构体类型
{
int x;
节点*左,*右;
};
Node*tree=NULL;
无效推送(int a,节点**Mytree)
{
if((*Mytree)==NULL){
(*Mytree)=新节点;
(*Mytree)->x=a;
(*Mytree)->left=(*Mytree)->right=NULL;
返回;
}
如果(a>(*Mytree)->x)将(a,&(*Mytree)->向右推;
否则按(a,&(*Mytree)->左键);
}
无效打印(节点*Mytree,int u)
{
如果(Mytree){
打印(Mytree->左侧,u+1);
对于(int i=0;is;
推送(s和树);
}

你难道不知道你的导师所说的“指定级别”是什么意思吗@ QWRRTY:我猜根节点级0,它下面的两个子节点,等等。YEP,一些CPP特征。根是0级,子级的父级+ 1等。如@ E.TIENEN所提到的。那么,如果你在C++中编程,你为什么要标记你的问题C?你知道如何编写一个函数来访问树中的每个节点吗?
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;
    }
}