C中二叉树的迭代器方法 [英] Iterator Method for Binary Trees in C
问题描述
我收到了以下说明:
向库中添加一个新方法,将函数应用于树中的每个值。 (这是树的迭代器方法。)
I've been given the following instruction:
Add a new method to the library that applies a function to every value in the tree. (This is an iterator method for trees.)
int bst_char_iterate(bst_char *t, char (*fun)(char item))
注意:只有传递给它的函数是单调的,才能通过此方法保留BST属性。每当
x< = y(箭头)f(x)< = f(y)时,函数f都是单调的。
Bst_char * t等同于指向树的指针,* fun等同于指向函数调用的指针,item是调用函数的值。
我设法得到了这个:
NB: The BST property will only be preserved by this method if the function passed to it is monotonic. A function f is monotonic whenever
x <= y (arrow) f(x) <= f(y).
"Bst_char *t" equating to a pointer to the tree, "*fun" equating to a pointer to a function call and "item" being the value of which the function is called upon.
I've managed to come up with this:
int bst_char_iterate(bst_char *t, char (*fun)(char item)) {
assert(t!=NULL);
struct node * p = t->root;
if (p!=NULL) {
p->item = fun(p->item);
p->left->item = bst_char_iterate(t,fun(p->left));
p->right->item = bst_char_iterate(t,fun(p->right));
} else {
return 0;
}
}
这是无法编译的,有很多错误(例如来自没有指针的指针)演员)。
请帮忙!
编辑:我已设法让它编译这段代码:
This cannot compile, with quite a few errors (such as "from pointer without a cast").
Please help!
I have managed to get it to compile with this code:
int bst_iterate(struct node *p, char (*fun)(char item)) {
if (p!=NULL) {
p->item = fun(p->item);
bst_iterate(p->left,fun);
bst_iterate(p->right,fun);
} else {
return 0;
}
}
int bst_char_iterate(bst_char *t, char (*fun)(char item)) {
assert(t!=NULL);
bst_iterate(t->root,(fun));
}
但我不知道如何在测试程序中实现它。
我试过:
But I've no idea how to implement it in the test program.
I've tried:
bst_char_iterate(t, fun);
bst_char_iterate(t, *fun);
bst_char_iterate(t->root, fun);
bst_char_iterate(t, fun(c));
推荐答案
但是我不知道如何在测试程序中实现它。
But I've no idea how to implement it in the test program.
保持简单:
Keeping it simple:
// the dumbest monotonic function...
char my_fun(char c)
{
return c;
}
int main()
{
bst_char * ptree;
// ...
// ... create the tree, make ptree pointing to it
// ...
bst_char_iterate(ptree, my_fun);
// ...
// ... free the tree
// ...
return 0;
}
bst_char_iterate(t, fun); // what type is t?
bst_char_iterate(t, *fun); // *fun is incorrect, use fun
bst_char_iterate(t->root, fun); // what type is root?
bst_char_iterate(t, fun(c)); // fun(c) is wrong, use fun
在上述所有情况下,什么是有趣
以及定义在哪里?
我在我的第一条评论中说,你需要显示编译器产生的确切错误信息。
And in all the above cases what is fun
and where is it defined?
As I said in my first comment, you need to show the exact error message the compiler produces.
这篇关于C中二叉树的迭代器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!