数据结构学习_树(2)

 Huffman树是二叉树的一种应用。Huffman树的总的带权路径长度最短。

b

6

c

d

7

5

2

4

11

18

下面是自己写的构造Huffman树的代码。

随着世界越来越开放,我想自己写的代码以后可能要和国外的人交流。因此在以后的代码编写过程中注释尽量用英语。

#include  < iostream >
#include 
< vector >
#include 
< algorithm >
#include 
< string >
using   namespace  std;

// the structure of the Huffman tree's nodes
typedef  struct  HFNode
{
    
int data;
    
struct HFNode* pLChild;
    
struct HFNode* pRChild;
}
HFNode;

HFNode EmptyNode 
=
{
    
0,
    NULL,
    NULL
}
;

// creat the rule for the sort() to compare all the elements in the vector
bool  SortRule(HFNode &  a, HFNode &  b)
{
    
if (a.data <= b.data)
        
return true;
    
else
        
return false;
}


// use the preprocessor  operator ## to creat the variables
#define  pHFNode(j) pHFNode##j

// print all the elements of the HFTree according pre order
void  PreOrderPrint(HFNode *  pRoot)
{
    
if (NULL != pRoot)
        cout 
<< pRoot->data << endl;
    
if (NULL != pRoot->pLChild)
        PreOrderPrint(pRoot
->pLChild);
    
else
        cout 
<< "@" << endl;
    
if (NULL != pRoot->pRChild)
        PreOrderPrint(pRoot
->pRChild);
    
else
        cout 
<< "@" << endl;;
}

int  main()
{    
    
const int NODENUM = 4;
                     vector
<HFNode> HFArray (NODENUM, EmptyNode);
    
int ValueArray[NODENUM] = {7524};

    
//provide data for all the nodes
    for (int i = 1; i <= NODENUM; i++)
    
{
        HFArray[i 
- 1].data = ValueArray[i - 1];
    }

    
int a, b, c ;
    a 
= b = c = 1;
    
while(HFArray.size() > 1)
    
{
        
//sort the vector and find the first and second of the smallest nodes
        sort(HFArray.begin(), HFArray.end(), SortRule);
        HFNode
* pHFNode(a) = new HFNode;
        memcpy(pHFNode(a), 
&HFArray[0], sizeof(HFNode));
        a
++;
        HFNode
* pHFNode(b) = new HFNode;
        memcpy(pHFNode(b), 
&HFArray[1], sizeof(HFNode));
        b
++;

        
//creat the node as a root for the selected two leaf nodes 
        HFNode* pHFNode(c) = new HFNode;
        pHFNode(c)
->data = pHFNode(a)->data + pHFNode(b)->data;
        pHFNode(c)
->pLChild = pHFNode(a);
        pHFNode(c)
->pRChild = pHFNode(b);
        c
++;

        
//erase the two nodes and push back the new root
        HFArray.erase(HFArray.begin(), HFArray.begin() + 2);
        HFArray.push_back(
*pHFNode(c));
    }

    HFNode Root 
= HFArray.front();
    PreOrderPrint(
&Root);
    getchar();
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值