2016-05-12 111 views
-1

我有一個二叉樹,其中每個節點是一個結構。該結構有一個字符串和一個數字。我需要找到最大的數字。我試過二叉樹和結構

int search_max(link h){ 
    int max = 0; 
    if (h->item->acc == max) 
     return max; 
    if (h->item->acc > max){ 
     max = h->item->acc; 
     return search_max(h->l); 
     return search_max(h->r); 
    } 
    else { 
     return search_max(h->l); 
     return search_max(h->r); 
    } 
} 

但它給出了分段錯誤。 link h是樹的頭部的鏈接,並且acc不能爲0.

+7

'return search_max(h-> l); return search_max(h-> r);'函數在第一個返回時退出,您不能在一行中使用2個返回...(死代碼) –

+1

您應該包含'link'的代碼以獲得更多有用的反饋。但有一件事,看起來你應該檢查'h'是否爲'NULL',然後解除引用。 – fvgs

回答

0

基本上你正在做的前序遍歷,但是最大的軌道是有問題的。對於每次遞歸,您應該檢查並返回當前及其兩個孩子中的最大節點。你也沒有檢查節點是否爲NULL,這就是你看到崩潰的原因,因爲樹的葉子節點的子節點是空節點。試試這個:

int search_max(link h) { 
    if (h == NULL) return INT_MIN; 
    int max = h->item->acc; 

    int maxl = search_max(h->l); 
    if (max < maxl) 
     max = maxl; 

    int maxr = search_max(h->r); 
    if (max < maxr) 
     max = maxr; 

    return max; 
} 
+0

非常感謝 – Daisy

0

您不能從連續兩次函數中,函數將首先退出return

還有沒有檢查樹的末尾,在下一次迭代時h->lh->r變爲NULL或未初始化,具體取決於您如何創建它。這給出了分段錯誤。

-1
#define MY_MAX(a,b) (a) > (b) ? (a) : (b) 
typedef struct link 
{ 
    int acc; 
    struct link *l, *r; 
} link_t; 

int search_max(link_t *h, int max) 
{ 
    if (h == NULL) return max; 
    if (h->acc > max) max = h->acc; 
    max = MY_MAX(search_max(h->l, max), search_max(h->r, max)); 
    return max; 
} 
int main(void) { 
    link_t root = { 1, 0, 0 }; 
    link_t l1 = { 2, 0, 0 }; 
    link_t l2 = { 3, 0, 0 }; 

    link_t l11 = { 5, 0, 0 }; 
    link_t l12 = { 1, 0, 0 }; 
    link_t l21 = { 9, 0, 0 }; 
    link_t l211 = { 13, 0, 0 }; 
    link_t l212 = { 0, 0, 0 }; 
    root.l = &l1; 
    root.r = &l2; 
    l1.l = &l11; 
    l1.r = &l12; 
    l2.l = &l21; 
    l21.l = &l211; 
    l21.r = &l212; 
    printf("max [%d]", search_max(&root,0)); 

    return 0; 
} 

https://ideone.com/PKbM0M

+0

@downvoter,小心解釋一下? – 4pie0

+0

@downvoter請解釋你的投票。 – 4pie0

+0

@downvoter任何線索? – 4pie0

0

你需要添加另一個參數currmax的功能。這將存儲最大值的當前值以進行比較。

int search_max(link h, int currmax){ 
    int max; 
    if (h == NULL) 
     return currmax; 
    else if (h->item->acc > currmax){ 
     currmax = h->item->acc; 

    max = search_max(h->l,currmax); 
    if (max > currmax) 
     currmax = max; 

    max = search_max(h->r, currmax); 
    if (max > currmax) 
     currmax = max; 

    return currmax; 
}