从森林里造一棵n元树
Build an n-ary tree from a forest
我让教授给我一份下学期的旧作业。这是关于建立一个家谱,然后找到两个给定节点之间的亲缘关系。家谱是关于龙珠的,所以每个龙珠都有一个父亲。
问题是输入是这样的:
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
使用映射保存输入信息。
查找祖先节点。
将子节点添加到祖先节点。
如果某个节点不是祖先节点,则不要为其构建树。
- 将树节点添加到向量向量中的 n 元树遍历的平均和最坏情况时间复杂度是多少?
- C++ - 对 n 元树的迭代
- C++ - 如何找到 n 元树的给定节点的深度
- 我该如何平衡一棵退化的树?C++数据结构
- 递归搜索n元树中的元素
- 在两棵二元树中计数相等的节点
- 设计缓存优化的 N 元树
- 如何将一组二进制树的迭代器划分
- 重建一棵树
- 如何从正常的BST继承一棵红黑树
- 在 n 元树 c++ 中查找给定节点的祖先
- 从森林里造一棵n元树
- 二进制搜索树 - 将一棵树复制到另一棵树中
- C 复制一棵二进制树
- 求一棵树的直径
- 在C++中从预购中构建一棵树
- 遍历一棵 n 元树
- 如何检查一棵树是否是另一棵树的子树
- 如何将一棵树划分为两个子树
- 在一棵有191个节点且高度为9的二叉树中找到一个键所需的最大比较次数是多少?