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

二叉树(5)HuffmanTree

时间:2020-02-19 15:20:27      阅读:62      评论:0      收藏:0      [点我收藏+]

标签:str   style   iostream   cpp   nod   nbsp   template   iter   std   

构建一棵 HuffmanTree。

 

测试代码 main.cpp:

#include <iostream>
#include "HuffmanTree.h"

using std::cout;
using std::endl;

int main()
{
    auto il = { 1,2,3,4,5,6,7,8,9 };

    HuffmanTree<int> ht(il.begin(), il.end());
    ht.levelTraversal();
    cout << endl;

    return 0;
}

 

头文件 "HuffmanTree.h":

#pragma once


#include <queue>

template<typename _Ty>
class HuffmanTree
{
    struct Node
    {
        _Ty weight;
        Node* left = nullptr;
        Node* right = nullptr;
        Node(const _Ty& _w) :weight(_w) {}
    };

public:
    HuffmanTree() = default;

    template<typename _Iter>
    HuffmanTree(_Iter _it1, _Iter _it2)
    {
        if (_it1 == _it2) return;
        std::priority_queue<Node*, std::vector<Node*>, comp> pq;
        while (_it1 != _it2)
        {
            Node* temp = new Node(*_it1);
            pq.push(temp);
            temp = nullptr;
            ++_it1;
        }
        while (true)
        {
            if (pq.size() == 1)
            {
                root = pq.top();
                return;
            }
            Node* temp = new Node(pq.top()->weight);
            temp->left = pq.top();
            pq.pop();
            temp->weight += pq.top()->weight;
            temp->right = pq.top();
            pq.pop();
            pq.push(temp);
            temp = nullptr;
        }
    }

    ~HuffmanTree() { clear(root); }

    void levelTraversal()
    {
        if (root == nullptr) return;
        std::queue<Node*> nodePointers;
        nodePointers.push(root);
        Node* cur = nullptr;
        while (!nodePointers.empty())
        {
            cur = nodePointers.front();
            std::cout << cur->weight << " ";
            if (cur->left != nullptr) nodePointers.push(cur->left);
            if (cur->right != nullptr) nodePointers.push(cur->right);
            nodePointers.pop();
        }
    }

    struct comp
    {
        bool operator ()(const Node* _n1, const Node* _n2) { return _n1->weight > _n2->weight; }
    };

private:
    void clear(Node*& _root)
    {
        if (_root == nullptr) return;
        clear(_root->left);
        clear(_root->right);
        delete _root;
        _root = nullptr;
    }

private:
    Node* root = nullptr;
};

 

二叉树(5)HuffmanTree

标签:str   style   iostream   cpp   nod   nbsp   template   iter   std   

原文地址:https://www.cnblogs.com/teternity/p/HuffmanTree.html

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