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))
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!
Edit: 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));