[] Huffman tree data structure

About error code

About the constructor teacher Huffman tree to the code and the original code book are wrong, I modified a little bit.
code show as below

template <class T, class E>HuffmanTree<T,E>::HuffmanTree(E w[], int n){
    //给出n个权值w[1]~w[n-1], 构造Huffman树
    MinHeap<T, HuffmanNode<T,E> > hp;   //使用最小堆存放森林的结点
    HuffmanNode<T, E> *parent=NULL,fir_temp, sec_temp, tmp,*first,*second;
    
    int i;
    root = new HuffmanNode<T, E>[2*n - 1];
    for (i = 0; i < n; i++)
    {//按棵逐步建立森林中的树木,并作为Huffman树的叶结点。数据放入森林
        tmp.data = w[i];
        tmp.leftChild = NULL;
        tmp.rightChild = NULL;
        tmp.parent = NULL;
        hp.Insert(tmp); //森林信息插入最小堆中
    }
    for (i = 0; i < n-1; i++){  //n-1趟, 建Huffman树   
        hp.RemoveMin(fir_temp); //根权值最小的树
        first = new HuffmanNode<T,E>;
        *first = fir_temp;//first指向对应的最小结点
        hp.RemoveMin(sec_temp);         //根权值次小的树
        second = new HuffmanNode<T,E>;
        *second = sec_temp;//second指向对应的次小结点
        parent = new HuffmanNode<T, E>;
        parent->leftChild = first;
        parent->rightChild = second;
        parent->data = first->data + second->data;  
        hp.Insert(*parent);     //新结点插入堆中
    }
    root = new HuffmanNode<T,E>;//建立根结点
    hp.RemoveMin(fir_temp);
    *root = fir_temp;

    //输出哈夫曼树中各个叶结点的哈夫曼编码
    cout<<"       root = "<<root->data<<endl;
    output(root,string(),cout);
    cout << endl;
    buildCode(root, "");//输出各叶结点的哈夫曼编码
}

Algorithm steps

1) If s is a leaf node will be assigned to it haffmancode, outputs, return
2) recursively left subtree, to give the sub-leaf nodes left Huffman coding
3) recursively right subtree, to give the right child leaf nodes Huffman coding

void HuffmanTree<T, E>::buildCode(HuffmanNode<T, E> *x, string s)
{
//在这里添加你完成任务的代码
    if (x->isLeaf()) //判断x是否为叶结点
    {
        x->haffmancode = s;
        cout << x->data << " 的哈夫曼编码为:" << x->haffmancode << endl;
        return;
    }
    else
    {
        buildCode(x->leftChild, s + '0'); 
        buildCode(x->rightChild, s + '1');
    }

}

operation result

Guess you like

Origin www.cnblogs.com/muyefeiwu/p/11845173.html