计算 C 中二叉树中的出现次数

标签 c struct tree binary-tree nodes

struct tree{
    struct node* root;
};

typedef struct tree* Tree;

struct node{
   int key;
   struct node* left;
           struct node* right;
};
typedef struct node* node;

我的问题是我需要实现的功能需要树而不是节点作为参数。

int count_occurrences(Tree t, int k){}

如果第一个参数是 Node 类型,我知道如何实现这个函数,但由于它需要一个 Tree 类型,我不知道如何在递归调用中传递 Tree 类型参数。

编辑:还有另一个问题。我无法直接访问结构字段,因为它们是在另一个文件(学校项目)中声明的。我可以访问一些功能,例如获取树的根、节点的左或右子节点等

Tree newtree();
int treeempty(Tree t);
Node root(Tree t);
int readInfo(Node v);
void setInfo(Node v, int x);
Node leftChild(Node v);
Node rightChild(Node v);

最佳答案

一种直接的方法是创建辅助函数:

int count_occurrences_helper(node d, int k) {
  /* You already know how to implement this. */
}

int count_occurrences(Tree t, int k) {
  return count_occurrences_helper(t->root, k);
}

关于计算 C 中二叉树中的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41418057/

相关文章:

c - virt_to_bus() 在 linux 内核模块编译中被弃用

c++ - 在 C++、结构或类中应该使用什么来创建链接列表

tree - 是否可以使用 Java 8 Streams 构建 Tree 数据模型

c++ - 通用 "out of bounds", "past end"迭代器

c - 如何从另一个线程调用 Gtk API?

有人可以解释这些 C 代码吗?

c++ - srand()的含义

c - 使用 union/结构在纯 C 中创建广义列表对象

c++ - 具有结构 vector 的类,其中包含相同的类

mysql - 从 mysql 获取二叉树的左侧