【发布时间】:2017-11-30 22:55:11
【问题描述】:
我正在寻找一种方法来按出现的顺序将字符串填充到我的二叉树中,并按照我将它们输入到我的树中的顺序访问它们。我只是想不出一种方法来创建这样一棵树。
我得到一个根节点,它分成两个分支,分支本身也创建了另外两个分支。等等。 我想要的只是创建一棵树,如果有意义的话,它会按照我输入的顺序保存我的输入。
我希望树看起来像这样:
A
/ \
B C
/ \ / \
D E F G
A、B、C、D、E、F、G 等是我需要存储在树中的随机文件名。 如何按出现的顺序将随机字符字符串存储在二叉树中?做这种事情的最好方法是什么?任何帮助将不胜感激。
这是我用 C 编写的代码,但它似乎不起作用。右手边被弄乱了,存储在第一个 B 叶子之后。使用注释的 printf 函数,您可以看到它产生了分段错误。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
struct node
{
char *titel;
struct node *A;
struct node *B;
};
int bitPos (int n)
{
return n & -n;
}
void display(struct node *leaf)
{
if (leaf != NULL)
{
display(leaf->A);
printf("%s\n",leaf->titel);
display(leaf->B);
}
}
void insert(char* titel, struct node **leaf, int nodeCount, int bitPos)
{
if (*leaf == 0)
{
*leaf = (struct node*)malloc(sizeof(struct node));
(*leaf)->titel = malloc(strlen(titel)+1);
strcpy((*leaf)->titel,titel);
(*leaf)->A = NULL;
(*leaf)->B = NULL;
}
else
{
int currentBit = (nodeCount >> bitPos) & 1;
if (currentBit == 0) {
// insert to left
insert(titel, &((*leaf)->A), nodeCount, bitPos - 1);
}
else
{
// insert to right
insert(titel, &((*leaf)->B), nodeCount, bitPos - 1);
}
}
}
int main(int argc, char const *argv[])
{
struct node *root = 0;
insert("root",&root,1,bitPos(1));
insert("chapter_1A",&root,2,bitPos(2));
insert("chapter_1B",&root,3,bitPos(3));
insert("chapter_2A",&root,4,bitPos(4));
insert("chapter_2B",&root,5,bitPos(5));
insert("chapter_3A",&root,6,bitPos(6));
insert("chapter_3B",&root,7,bitPos(7));
insert("chapter_4A",&root,8,bitPos(8));
insert("chapter_4B",&root,9,bitPos(9));
display(root);
//printf("%s\n",root->B->A->titel);
return 0;
}
输入: 在主函数中看到的输入。
root => chapter_1A => chapter_1B => chapter_2A => chapter_2B and so on.
应该是输出(没有章节_):
root
/ \
1A 1B
/ \ / \
2A 2B 3A 3B
/ \
4A 4B
使用显示功能的程序实际输出:
chapter_4B
chapter_4A
chapter_2B
chapter_2A
chapter_1A
root
chapter_1B
chapter_3A
chapter_3B
【问题讨论】:
-
即使如此,节点似乎也被向后插入(即,右子节点填充在左节点之前)。至少要考虑到 ch 4 在显示中的 ch 3 之前的事实。
-
对于在
main()中调用它的情况,您期望bitPos()的输出是什么? -
数据结构应该适合问题集。由于希望能够按照插入的顺序检索数据,(这与二叉树无关)强烈建议使用指针数组,每个指针指向一个字符串。如果每个条目都是使用
realloc()和strdup()生成的,那么整个过程就变得非常简单了
标签: c tree binary-tree nodes