繁体   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