tripleq
tripleq

Reputation: 99

n-ary tree searching function

I'm trying to make a function for n-ary tree searching, but it doesn't work well, it returns wrong node after level 2. Anyone knows why?

Here is node implementation

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

And there is a function

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]);
}

Upvotes: 0

Views: 1308

Answers (1)

eyalm
eyalm

Reputation: 3366

You return the child that holds the requested node but not the node itself.

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

Upvotes: 2

Related Questions