标题:哈夫曼树创建
只看楼主
i多子妹师南
Rank: 1
来 自:江苏
等 级:新手上路
帖 子:12
专家分:4
注 册:2016-11-13
结帖率:85.71%
已结贴  问题点数:5 回复次数:1 
哈夫曼树创建
#include "stdafx.h"
#include<stdlib.h>
typedef char ElemType;//要加分号
void creathafuman(int n);
typedef struct node
{
    ElemType data;
    int weight;
    int parent;
    int lchild;
    int rchild;

}htnode;

int main()
{
   
    creathafuman(3);

    return 0;
}
void creathafuman(int n)//n是哈夫曼树叶子结点个数
{
    htnode *p;

   
    p = (htnode *)malloc((2 * n - 1) * sizeof(htnode));
    int i;             for (i = 0; i < 2*n - 1; i++)
    {
        p[i].parent = p[i].lchild = p[i].rchild = -1;
    }
    for (i = 0; i < n; i++)
    {
        scanf_s("%d", &p[i].weight,1);//输入叶子结点的权重
    }
    int min1 = 0, min2 = 0, e, f;//min1,min2存储最小权重值,e ,f存储最小权重的数组下标
    int j;
    for (j = 0; j < n; j++)
    {
        for (i = 0; i<=n+j; i++)
        {
            while (p[i].parent == -1)
            {
                if (min1 == 0)
                {
                    min1 = p[i].weight;
                    e = i;
                    break;
                }
                if (min2 == 0)
                {
                    min2 = p[i].weight;
                    f = i;
                    break;
                }
                if (min1 >= min2)
                {
                    if (p[i].weight< min1)
                    {
                        min1 = p[i].weight;
                        e = i;
                    }
                }
                else
                    if (p[i].weight < min2)
                    {
                        min2 = p[i].weight;
                        f = i;
                    }


            }
        }
        p[n + j + 1].weight =(min1 + min2);
        p[n + j + 1].lchild = e;
        p[n + j + 1].rchild = f;
        p[e].parent = n + j + 1;
        p[f].parent = n + j + 1;
    }
    printf("%d", p[2 * n - 2].weight);
}
程序中的函数可以自己先输入n个叶子结点的权重,然后在连续数组中产生剩余n-1个哈夫曼树的结点,问题是我调用该函数输入三个叶子结点的值,输入三个值后仍能继续输入,按erter不会输出最后一个结点的权重,即执行不到程序最后的printf("%d", p[2 * n - 2].weight);
搜索更多相关主题的帖子: include return parent 叶子 
2017-03-31 23:41
寒风中的细雨
Rank: 17Rank: 17Rank: 17Rank: 17Rank: 17
等 级:贵宾
威 望:66
帖 子:1710
专家分:8645
注 册:2009-9-15
得分:5 
单步调试
2017-04-01 00:49



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-475699-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.182777 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved