【发布时间】:2017-12-11 17:46:54
【问题描述】:
我正在尝试将存储在我的二叉搜索树的每个节点中的数据递归地插入到一个数组中,并通过代码的 InOrder 逻辑进行排序。
这是我正在使用的两个函数的 sn-p。 “bst_getordered”的参数和类型不能改变,只能改变它的内容。可以以任何必要的方式更改“node_getordered”。
void bst_getordered(bst* b, void* v)
{
int i = 0;
if (b == NULL || v == NULL) {
return;
}
node_getordered(b->top, (char*) v, i);
}
int node_getordered(bstnode* node, char* v, int i)
{
if (node == NULL) {
return i;
}
node_getordered(node->left, v, i);
v[i] = (char) node->data;
i++;
node_getordered(node->right, v, i);
return i;
}
它应该将树中的所有数据排序后存储到数组中。但是它没有这样做,我不知道为什么......我想我应该使用双指针来增加地址,但我不知道如何去做......我的语法知识缺乏那个领域...
[编辑 1] 这是我用来确保代码正常工作的测试程序的 sn-p:
void test_getordered(void)
{
int i, sc;
char words1[WORDS][STRSIZE] = {"it", "is", "a", "truth",
"universally", "acknowledged", "that", "a", "single", "man", "in",
"possession", "of", "a", "good", "fortune", "must", "be", "in",
"want",
"of", "a", "wife"};
char words2[WORDS][STRSIZE];
bst* b = bst_init(STRSIZE, mystrcmp, myprintstr);
bst_insertarray(b, words1, WORDS);
assert(bst_size(b)==18);
bst_getordered(b, words2);
printf("%lu %s\n", sizeof(words2), words2[0]);
for(i=0; i<17; i++){
sc = strcmp(words2[i], words2[i+1]);
assert(sc<0);
}
bst_free(&b);
assert(b==NULL);
}
[EDIT 2] 这些是我的节点和树的结构。我怀疑我需要通过 tree->elsz 以某种方式增加计数器才能正确遍历数组:
struct bstnode {
void* data;
struct bstnode* left;
struct bstnode* right;
};
typedef struct bstnode bstnode;
struct bst {
bstnode* top;
/* Data element size, in bytes */
int elsz;
};
typedef struct bst bst;
【问题讨论】:
-
“v[i] = (char) node->data;i++;”位绝对应该用正确的代码替换,我就是想不通...
标签: c binary-search-tree void-pointers inorder double-pointer