生成哈夫曼树

给定权集{5,7,2,3,6,8,9}构造哈夫曼树

#include <stdio.h>
#include <stdlib.h>
#define ElemType int
#define MAXSIZE 20
#define length 7
typedef struct HFNode{
    ElemType weight;
    struct HFNode *lchild,*rchild;
}HFNode,*HFTree;
HFTree CreatHFTree(ElemType s[MAXSIZE]){
    HFTree hftarr[MAXSIZE];
    HFTree hft,root=NULL;
    for(int i=0;i<length;i++){
        hft=(HFTree)malloc(sizeof(HFNode));
        hft->weight=s[i];
        hft->lchild=NULL;
        hft->rchild=NULL;
        hftarr[i]=hft;
    }
    for(int i=1;i<length;i++){
        int w1=-1,w2;//w1为最小节点的下标,w2为次最下节点的下标
        for(int j=0;j<length;j++){
            if(hftarr[j]!=NULL&&w1==-1){
                w1=j;
                continue;
            }
            if(hftarr[j]!=NULL){
                w2=j;
                break;
            }
        }
        for(int j=w2;j<length;j++){
            if(hftarr[j]!=NULL){
                if(hftarr[j]->weight<hftarr[w1]->weight){
                    w2=w1;
                    w1=j;
                }
                else if(hftarr[j]->weight<hftarr[w2]->weight){
                    w2=j;
                }
            }
        }//找出最小权重的两个节点
        root=(HFTree)malloc(sizeof(HFNode));
        root->weight=hftarr[w1]->weight+hftarr[w2]->weight;
        root->lchild=hftarr[w1];
        root->rchild=hftarr[w2];
        hftarr[w1]=root;//将生成的新树指针指向w1
        hftarr[w2]=NULL;
    }
    return root;
}//生成哈夫曼树
void visit(HFTree &T){
    if(T!=NULL){
        printf("%d ",T->weight);
    }
}
void PreOrder(HFTree &T){
    if(T){
        visit(T);
        PreOrder(T->lchild);
        PreOrder(T->rchild);
    }
}
int main(){
    ElemType s[MAXSIZE]={5,7,2,3,6,8,9};
    HFTree T;
    T=CreatHFTree(s);
    PreOrder(T);
}

 

转载于:https://www.cnblogs.com/Yshun/p/11342646.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值