码迷,mamicode.com
首页 > 其他好文 > 详细

哈夫曼建树

时间:2018-05-22 22:04:33      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:return   const   namespace   size   pop   tor   fat   new   输入   

输入是各个叶子节点的值,第一个是数值的个数,然后先序遍历这棵树

#include<iostream>
#include<queue>
using namespace std;
int n;
struct tree
{
    int data;
    tree * lson;
    tree * rson;
}*ans;

struct f
{
    tree * father;
    int num;

    bool operator<(const f x)const
    {
        return num>x.num;
    }
}exa;

priority_queue<f>q;

void init()
{
    cin>>n;
    int x;
    for(int i=1;i<=n;i++){
        cin>>x;
        tree * bitree = new tree;
        exa.father=bitree;
        exa.num=x;
        bitree->data=x;
        bitree->lson=NULL;
        bitree->rson=NULL;
        q.push(exa);
    }
}

void build()
{
    f tree1,tree2;
    while(q.size()>1){
        tree1=q.top();q.pop();
        tree2=q.top();q.pop();
        tree * newtree = new tree;
        exa.num=newtree->data=tree1.num+tree2.num;
        newtree->lson=tree1.father;
        newtree->rson=tree2.father;
        exa.father=ans=newtree;
        q.push(exa);
    }
}

void view(tree * s)
{
    if(s==NULL){return;}
    cout<<s->data<<endl;
    view(s->lson);
    view(s->rson);
}

int main()
{
    init();
    build();
    view(ans);
}

// 7 7 1 3 9 5 4 8

 

哈夫曼建树

标签:return   const   namespace   size   pop   tor   fat   new   输入   

原文地址:https://www.cnblogs.com/ZGQblogs/p/9074011.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!