我试图遍历一棵多路树,但我试图以一种有效的方式来做,但这并没有真正帮助我,更重要的是我想递归地做。
我的想法是这样的:我有一棵树,一个孩子和它的兄弟姐妹。我想递归地和孩子们一起下去,然后只要它有兄弟姐妹也递归地去他们身上。
在这里,我将向您介绍我的数据结构以及我如何尝试实现它。这是一个完整的功能“可测试”,它还将创建一张照片供您查看树并使用代码:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define SIZE 100
typedef struct tree {
int value;
struct tree *child, *sibling;
} *Tree;
Tree initTree(int value) {
Tree root = malloc(sizeof(struct tree));
root->value = value;
root->child = NULL;
root->sibling = NULL;
return root;
}
void drawTreeHelper(Tree tree, FILE* stream) {
Tree tmp;
if (tree == NULL) {
return;
}
fprintf(stream, " %ld[label=\"%d\", fillcolor=red]\n", (intptr_t) tree, tree->value);
tmp = tree->child;
while (tmp != NULL) {
fprintf(stream, " %ld -> %ld \n", (intptr_t) tree, (intptr_t) tmp);
drawTreeHelper(tmp, stream);
tmp = tmp->sibling;
}
}
void drawTree(Tree tree, char *fileName) {
FILE* stream = fopen("test.dot", "w");
char buffer[SIZE];
fprintf(stream, "digraph tree {\n");
fprintf(stream, " node [fontname=\"Arial\", shape=circle, style=filled, fillcolor=yellow];\n");
if (tree == NULL)
fprintf(stream, "\n");
else if (!tree->child)
fprintf(stream, " %ld [label=\"%d\"];\n", (intptr_t) tree, tree->value);
else
drawTreeHelper(tree, stream);
fprintf(stream, "}\n");
fclose(stream);
sprintf(buffer, "dot test.dot | neato -n -Tpng -o %s", fileName);
system(buffer);
}
int main() {
int i;
char buffer[SIZE];
Tree *forest = malloc(5 * sizeof(Tree));
for (i = 0; i < 5; i++) {
forest[i] = initTree(i);
}
forest[4]->child = forest[3];
forest[4]->child->sibling = forest[2];
forest[1]->child = forest[0];
forest[1]->child->sibling = forest[4];
for (i = 0; i < 5; i++) {
sprintf(buffer, "tree_%d.png", i);
if (forest[i]) {
drawTree(forest[i], buffer);
}
}
return 0;
}
我要创建的功能保持不变,即:
Tree findChild(Tree root, int value)
{
if(!root) return NULL;
if(root->value == value) return root;
return findChild(root->child, value);
Trie iter = root;
while(iter)
{
return findChild(iter->sibling, value);
iter = iter->sibling;
}
}
我希望找到孩子,但如果节点不是根的直接孩子,它会返回 NULL。我要创建的功能的期望:在树中以最有效的方式找到孩子。