【发布时间】:2017-08-11 06:55:43
【问题描述】:
在我的程序中,我有一个定义如下的二叉树:
struct node {
char value;
struct node *left, *right;
};
在我的程序中,我正在尝试编写一个函数,该函数以索引顺序(从上到下,从右到左遍历)返回每个节点值的字符串。
为此,我编写了以下函数:
char *to_string_util(struct node *root, char *str) {
if (!root) return str;
*str++ = root->value;
// If not NULL
if (root->left) to_string_util(root->left, str);
if (root->right) to_string_util(root->right, str);
return str;
}
这似乎应该有效,但可惜它没有。我已经通过使用数组索引来使其工作,这工作但不受欢迎,因为它需要引入另一个变量。
这是有效的版本:
char *to_string_util(struct node *root, char *str, int *cur_pos) {
if (!root) return str;
str[(*cur_pos)++] = root->value;
if (root->left) to_string_util(root->left, str, cur_pos);
if (root->right) to_string_util(root->right, str, cur_pos);
return str;
}
给定树:
+
/ \
* *
/ \ / \
a a b b
结果应该是:+*aa*bb
需要注意的一点是,我在另一个函数中调用了这个函数,它在它的末尾附加了一个空字符,这不应该影响输出,但我认为可能值得一提。
为什么使用数组索引的第二个版本可以工作,而第一个却不行?
【问题讨论】:
标签: c pointers binary-tree