2017-05-14 26 views
0

我想要通往二叉搜索樹中最大葉子的途中的所有節點。節點只包含正數。通往BST中最大葉子的元素總和

#include <stdio.h> 
#include <stdlib.h> 
#include <malloc.h> 
#include <time.h> 

typedef int ElType; 

typedef struct Tree { 
    ElType key; 
    struct Tree *left; 
    struct Tree *right; 
} Tree; 

Tree* InsertBST(Tree* t, int k) 
{ 
    if (t == NULL) { 
     Tree* w = (Tree*) malloc(sizeof(Tree)); 
     w->key = k; 
     w->left = NULL; 
     w->right = NULL; 
     return w; 
    } 

    if (k <= t->key) 
     t->left = InsertBST(t->left, k); 
    else 
     t->right = InsertBST(t->right, k); 

    return t; 
} 

int SumMaxOfBST(Tree* t, int *sum_max) 
{ 
    if (t == NULL) { 
     *sum_max = -1; 
     return *sum_max; 
    } 

    if (t->right == NULL) { 
     *sum_max += t->key; 
     return *sum_max; 
    } 

    *sum_max += t->key; 

    *sum_max += SumMaxOfBST(t->right, sum_max); 
    return *sum_max; 
} 

int main() 
{ 
    int i; 
    srand (time(NULL)); 

    Tree* t = NULL; 
    for (i = 0; i < 20; i++) 
     t = InsertBST(t, rand() % 1000); 

    int sum_way = 0; 
    int a = SumMaxOfBST(t, sum_way); 

     printf("Sum on the way to the largest leaf %d:\n", a); 

    return 0; 
} 

這退出非零狀態。我強烈的懷疑是,我已經拙劣地使用了指針,但是,在使用指針的幾次重寫和視頻之後,我似乎仍然不知道發生了什麼。如果我理解正確,*sum_max += x應該增加sum_max的值x。我在哪一點使用指針?

+1

你的編譯器應該在調用'int a = SumMaxOfBST(t,sum_way);'時抱怨'sum_way'之前沒有'&'。注意你的編譯器警告 - 編譯器是對的,你錯了,至少在C編程職業的這個階段。 –

+0

另外,''聲明'malloc()'等。除非您使用標題的擴展功能,否則不需要包含「」。此外,您的代碼無法讓您驗證您得到的答案是否正確;你不打印樹,所以你無法知道你的計算是否正確。 –

回答

2

我不明白你爲什麼把一個int指針作爲參數SumMaxOfBST的參數,我認爲這樣寫的函數更簡單。

int SumMaxOfBST(Tree* t) 
{ 
    if (t == NULL) { 
     return 0; 
    } 
    if (t->right == NULL) { 
     return t->key; 
    } 
    return t->+key + SumMaxOfBST(t->right); 
} 

而且在你main,你傳遞sum_way這是一個int,而SumMaxOfBST預計的int*。相反,您應該通過&sum_way

+0

謝謝,這的確比我的嘗試要乾淨得多。 – Zelazny