从森林里造一棵n元树

Build an n-ary tree from a forest

本文关键字:一棵 元树 森林      更新时间:2023-10-16

我让教授给我一份下学期的旧作业。这是关于建立一个家谱,然后找到两个给定节点之间的亲缘关系。家谱是关于龙珠的,所以每个龙珠都有一个父亲。

问题是输入是这样的:

First name is the parent  Second name is the child
Iolin                     Lyre
Iolin                     Piyano
Batu                      Iolin
Batu                      Okiat
Ollusc                    Xylo
Organa                    Murd
Piccoro                   Ollusc
Piccoro                   Rombone
Rombone                   Organa

所以我必须有两棵树,一棵由皮科罗担任首领(他总是一棵树的首领),另一棵由未知首领组成。

问题是,当我试图创建树时,我遇到了麻烦,我知道我有两个根,但正如你所看到的,输入不按顺序,所以在我读取并创建其父节点之前,我会有没有父节点的节点。例如,我创建了Ollusc和它的子Xylo,然后是Organa和Murd,但我只有一个根来表示那棵树(我也不知道它们是否在同一棵树上),所以我不知道如何"保存"这些节点,以便稍后将它们连接起来,Organa和Rombone也是如此,Organa将在某个地方,直到我创建Rombone,然后将他与Organa连接起来。

Batu------>NULL
/     
Iolin--->Okiat->NULL
/   
Lyre-->Piyano->NULL
Piccoro-----> NULL
/       
Ollusc--->Rombone->NULL
/          /
Xylo->NULL Organa->NULL
/
Murd->NULL

我想把节点保存到队列或堆栈中,因为在连接它们之前,我不知道有多少节点会漂浮在某个地方,但把它们保存到队列中,然后呢?,因为当我想到我的下一步时,我不知道该怎么办。也许将一个节点存储到队列中,直到出现一个节点Parent,然后从队列中取出该节点,但将其FIFO排队,我认为这没有太大帮助,因为如果我需要取出第二个节点,或者第三个节点,而不是前一个节点,该怎么办。所以也许可以将它们存储到辅助列表中?如果它们没有父节点并且不是根节点,我应该将节点添加到列表、队列、堆栈中,对吗?还是应该将根添加到列表、队列、堆栈中?因为我用根来建树在第一棵树上,我的根是Iolin,直到巴图出现,我把它改成巴图在第二棵树中,根永远是Piccoro,但从Piccoro开始建一棵树有点困难,因为我不知道他的孩子的

你觉得怎么样?我该怎么办?你有更好或其他的想法吗?

int main(int argc, char const *argv[])
{
FILE *fpInput,*fpOutput;
fpInput = fopen("input.in","r");
fpOutput = fopen("output.out","w");
if ((fpInput == NULL)){ printf("Open File Errorn"); exit(1); }
// To read a line of the file
char *fpInputString;
char *parentInput, *childInput;
// Because i dont know the number of lines that comes next, read until a number is found
// That number is the number of consult of kinship about namekians
fpInputString = inputString(fpInput,5);
while ((strlen(fpInputString) != 1) && (strlen(fpInputString) != 2) && (strlen(fpInputString) != 3))
{           
parentInput = strtok(fpInputString," ");
childInput  = strtok(NULL,"");
fpInputString = inputString(fpInput,5);
}

fclose(fpInput);
fclose(fpOutput);
return 0;
}

InputString函数从文件中读取整行

tree.h

// Struct of a node
struct treeNode
{
// Name
char *name;
// Pointers
struct treeNode *parent;
struct treeNode *firstChild;
struct treeNode *nextSibling;
struct treeNode *prevSibling;
};

如果你能帮助我,我将非常感谢,我知道这可能很难理解我或我的代码

但我真的很想学习关于编码的新东西,我不知道如果我用c++做这个作业是否会更好,因为c没有STL

使用映射保存输入信息。

查找祖先节点。

将子节点添加到祖先节点。

如果某个节点不是祖先节点,则不要为其构建树。