【问题标题】:Count occurrences in binary tree in C在 C 中计算二叉树中的出现次数
【发布时间】:2017-01-01 18:48:17
【问题描述】:
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);

【问题讨论】:

  • 你可以有一个接受树的前端函数和一个接受节点的递归函数。从前端调用带有根节点的递归函数。
  • 为什么需要递归调用?只需从根开始循环遍历树,直到到达结尾(这可能由rightbeeing NULL 指示)。另外,用 typedef 隐藏指针类型的事实可能会让人困惑。

标签: c struct tree binary-tree nodes


【解决方案1】:

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

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 中(不能移动它们,这是给学校的)。我可以访问一些功能,例如获取树的根,获取根的左孩子或右孩子
  • 不能直接访问struct字段是什么意思?它们在什么文件中定义并不重要。
  • 例如我不能做t->root,但我必须调用函数root(t)
  • 在这种情况下,只需将return count_occurrences_helper(t->root, k); 替换为return count_occurrences_helper(root(t), k);,解决方案将允许调用count_occurrences_helper() 作为递归函数。
  • 但是你之前写过“如果第一个参数是Node类型我知道怎么实现这个函数”...所以count_occurrences_helper()函数的第一个参数是node d...有什么问题?
猜你喜欢
  • 2021-06-11
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 2020-03-23
  • 1970-01-01
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
相关资源
最近更新 更多