簡體   English   中英

帶結構的二叉樹(C 語言)

[英]Binary tree with structs (in C)

我有一個二叉樹結構。 結構是

    typedef struct hashtag {
        char *name;
        int acc;
    } *Item;

節點由字符串組織。 我想打印具有最高 acc 但按字母順序排列的節點。 到目前為止我的代碼:

    Item search_max(link h) {
        int max;
        char *word;
        Item hashtag = (Item)malloc(sizeof(struct hashtag));
        Item left = (Item)malloc(sizeof(struct hashtag));
        Item right = (Item)malloc(sizeof(struct hashtag));
        hashtag = h->item;
        max = h->item->acc;
        word = h->item->name;
        if (h == NULL) 
            return 0;
        left = search_max(h->l);
        if (max == left->acc && less(left->name, word))
            word = left->name;
        if (max < left->acc){
            max = left->acc;
            word = left->name;
        }
        right = search_max(h->r);
        if (max == right->acc && less(right->name, word))
            word = right->name;
        if (max < right->acc){
            max = right->acc;
            word = right->name;
        }
        hashtag->acc = max;
        hashtag->name = word;
        return hashtag;
    }

h 是樹的頭部,less 是

    #define less(a,b) (strcmp(a,b) < 0)

鏈接是

    typedef struct node{
        Item item;
        struct node *l;
        struct node *r;
    } *link;

它給出了一個分段錯誤(核心轉儲)。 以前,我嘗試了相同的代碼,但沒有為左或右標簽分配內存(相同的錯誤)。

您正在為 Item 指針分配內存,然后覆蓋這些指針。 您有兩種選擇:您可以使用項目值,也可以正確使用指針:

對於第一個選擇,您必須從 Item typedef 中刪除 * 並更改 Items 的所有用法。 對於第二個選擇(在這種情況下更容易),您應該從 search_max 中刪除所有 malloc。 然后使用:

Item left = search_max(h->l);
...

請注意,您不能在本地檢查第二個條件(字典字符串順序)。 相反,您再次有兩個選擇:將所有具有最高 acc 值的條目收集到另一個集合中,然后當您完成樹時,遍歷該集合以找到該單個字符串。 第二種選擇:通過對 search_max 的所有調用遞歸傳遞信息 - 信息是當前字符串及其 acc 值。

結果要么是當前節點中的項,要么是其左子樹或右子樹下的項。 分而治之:(為了清晰和理智,我刪除了類型化的指針)

注意:不需要 malloc()。 您只是在檢查現有的樹,而不是向其中添加任何內容。


struct item {
        char *name;
        int acc;
        };

struct node {
        struct item *item;
        struct node *left, *right;
        };

int items_cmp( struct item *one, struct item *two)
{
if (one->acc < two->acc) return -1; /* two is better */
if (one->acc > two->acc) return 1;  /* one is better */
return strcmp(one->name, two->name);
}

struct item * find_max( struct node *np)
{
struct item *ret, *sub;

if (!np) return NULL; /* stop the recursion ! */

ret = np->item;
sub = find_max(np->left);
if ( sub && items_cmp(ret, sub) > 0)
        ret = sub;

sub = find_max(np->right);
if ( sub && items_cmp(ret, sub) > 0)
        ret = sub;

return ret;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM