带结构的二叉树(在C中)

时间:2016-05-13 11:22:02

标签: c struct binary-tree binary-search-tree

我有一个结构的二叉树。结构是

    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是树的头部,少了

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

和链接

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

它给出了分段错误(核心转储)。以前我尝试过相同的代码而没有为hashtag,left或right(相同的错误)分配内存。

2 个答案:

答案 0 :(得分:1)

您正在为Item指针分配内存,然后覆盖指针。 您有两种选择:您可以使用项目值,也可以正确使用指针:

对于第一个选择,您必须从Item typedef中删除*并更改Items的所有用法。对于第二种选择(在这种情况下更容易),您应该从search_max中删除所有malloc。然后使用:

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

请注意,您可以不在本地检查第二个条件(词典字符串顺序)。相反,您又有两个选择:将具有最高acc-value的所有条目收集到另一个集合中,然后当您完成树时,通过该集合查找该单个字符串。第二种选择:递归传递所有对search_max的调用信息 - 信息是当前字符串及其acc值。

答案 1 :(得分:0)

结果是当前节点中的项目,或者是左下子树下的项目。划分和征服:(为了清晰和理智,我删除了typedeffed指针)

注意:不需要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;
}