2016-05-12 20 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); 
    } 
} 

しかし、それはセグメント違反を与えます。 はツリーの先頭のリンクであり、accは0にはできません。

+7

return search_max(h-> l); return search_max(h-> r); '関数は最初の戻り値で終了し、2つの戻り値を連続して使用することはできません。 ) –

+1

もっと便利なフィードバックを得るには 'link'のコードを含めるべきです。しかし、ある意味では、逆参照する前に 'h'が' NULL'であるかどうかを確認する必要があります。 – fvgs

答えて

0

基本的には予約注文トラバーサルを行っているが、最大のトラックには問題があります。各再帰について、現在のノードとその2つのノードの中の最大のノードをチェックして返さなければなりません。また、ノードが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

関数から2回連続してreturnを呼び出すことはできません。関数は最初にreturnで終了します。

また次の反復h->lまたはh->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; 
}