c - C 中的二叉树 : Traversal specified level

标签 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**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;
     }

如果可能,请建议我执行此任务的函数。

最佳答案

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

关于c - C 中的二叉树 : Traversal specified level,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20229870/

相关文章:

algorithm - 在没有额外类(class)的情况下找到二叉树中的最深节点?

algorithm - 查找二叉树的第 n 个中序节点,其中每个节点包含其子树中左节点的数量

创建节点链接列表

c - 使用整数值作为哈希表的键有多愚蠢?

c - 使用标准 C 套接字 API 判断文本字符串是 IPv6 地址还是 IPv4 地址

c - 在二叉树中插入节点时程序崩溃

java - "Continuous"二叉搜索树

c - 数组指针作为参数传递给其他函数时会更改值

c - 如何在全局变量中获得缓冲区溢出?

java - 制作一棵树并排序它的数字