c - n叉树搜索函数

标签 c tree

我正在尝试为 n-ary 树搜索创建一个函数,但效果不佳,它在第 2 级之后返回错误的节点。有人知道为什么吗?

这里是节点实现

typedef struct node
{
    char name[30];
    int year;
    struct node* ptr;
    struct node* p[10];
} node;

还有一个函数

node *search(node *p, char* name, int year)
{
    int i, n;
    if(p == NULL)
        return (NULL);

    if((!strcmp(p->name, name) && (p->year == year))
        return (p);

    n = number(p); \\returns number of childs

    for(i = 0; i < n; i++)
        if(search(p->p[i], name, year))
            return (p->p[i]);
}

最佳答案

您返回包含所请求节点的子节点而不是节点本身。

for(i = 0; i < n; i++)
{
    if ((p2 = search(p->p[i], name, year)))
            return p2;
}
return NULL;

关于c - n叉树搜索函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21588796/

相关文章:

c - Linux 共享内存同步

c - 如果不处理 printf 会发生什么

c++ - 二叉搜索树删除而不复制

javascript - "between"CSS/jQuery 选择器

algorithm - AVL 树 : How to do index access?

c++ - 在 C++ 中使用子列表实现树

c - 使用 C 将文件内容分配给变量?

c - 如何区分可执行文件和自动运行文件

使用 typedef 结构时的 C 设计风格

performance - 快速遍历ACL的策略