• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

kaikai向前走

转职任务完成。崭新fn诞生
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

建立huffman树,当然用堆排序

闲着去逛论坛,看到有人问建huffman树。记得当初学数据结构时我没写过,所以也来试试。不过这个当作业实在是太迟了:)

/**//*
做huffman用堆排序应该效率最高了吧,不过自己写一个太麻烦,就直接用stl算了:
*/

#include 
<cstdio>
#include 
<vector>
#include 
<algorithm>

template
< class Type >
struct node
{
    node 
*left, *right;
    
int value;
    
const Type *data;
    
struct ptrcmp // 仿函数,用于堆排序的比较
    {
        
bool operator () (const node* a, const node* b)
        
{
            
return a->value > b->value; // 最小堆
        }

    }
;
}
;

template
< class Type >
node
< Type >* buildHuffmanTree(const Type data[], int count)
{
    typedef node
< Type > Node;
    
    
// 初始化堆
    ::std::vector< Node* > heap(count, NULL);
    heap.clear();
    
for(int i= 0; i < count; i++)
    
{
        Node 
*n = new Node;
        n
->left = NULL;
        n
->right = NULL;
        n
->data = &data[i];
        n
->value = data[i]; // 如果Type不能转化到int,则必须重载一个operator int()
        heap.push_back(n);
    }

    ::std::make_heap(heap.begin(), heap.end(), Node::ptrcmp());

    
// 用堆排序找到最小的2个元素,建立它们的父节点
    while(heap.size() > 1)
    
{
        Node 
*n1, *n2, *t;
        ::std::pop_heap(heap.begin(), heap.end(), Node::ptrcmp());
        n1 
= heap.back();
        heap.pop_back();
        ::std::pop_heap(heap.begin(), heap.end(), Node::ptrcmp());
        n2 
= heap.back();
        t 
= new Node; // 父节点
        t->left = n1;
        t
->right = n2;
        t
->value = n1->value + n2->value; // 权值为孩子们权的和

        
// 再把这个父节点放回堆
        heap.back() = t;
        ::std::push_heap(heap.begin(), heap.end(), Node::ptrcmp());
    }

    
return heap.front();
}


template
< class Type >
void destoryTree(node< Type >* root)
{
    
if (root->left) destoryTree(root->left);
    
if (root->right) destoryTree(root->right);
    delete root;
}


template
< class Type >
void drawTree(node< Type >* root)
{
    printf(
"%d",root->value);
    
if (root->left)
    
{
        printf(
"(");
        drawTree(root
->left);
        printf(
",");
    }

    
if (root->right)
    
{
        drawTree(root
->right);
        printf(
")");
    }

}


// 测试用例
int main()
{
    
int data[] = {2,3,4,5,1,2,3,65,8,2,};
    node
< int > *root = buildHuffmanTree(data, sizeof(data)/sizeof(data[0]));

    drawTree(root); 
// 结果为:95(30(13(6(3,3),7(3(1,2),4)),17(8,9(4(2,2),5))),65)
    printf("\n");

    destoryTree(root);
    
return 0;
}

posted on 2005-07-14 21:01  kaikai  阅读(1667)  评论(1)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3