2014-02-05 58 views
0

我試圖做一個n元樹搜索的功能,但它不能很好地工作,它會在2級後返回錯誤的節點。任何人都知道爲什麼?n元樹搜索功能

這裏是節點實現

​​

而且還有一個功能

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

如果for'loop'search'確實返回'return',會發生什麼?你沒有處理這種情況。另外,什麼是'ptr'用於,因爲它沒有在代碼中提到? – Sean

+0

你是什麼意思如果得到返回? ptr是指向父節點的指針,我需要它用於其他功能。 – tripleq

回答

2

你返回保存請求的節點,但不是節點本身的孩子。

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