huffman tree

// todo

#include <iostream>
using namespace std;

// buidl a huff tree with an Node array
// to get the huffcode, should traverse up the tree from leafs
class Node
{
public:
    Node() :left(0), right(0), parent(0),weight(-2){}
    Node * left, *right, *parent;
    int weight;
};

class HuffTree
{
public:
    HuffTree(int arr[], int len) :leaf(len), tree(0), root(0){ initialize(arr); this->build_huff(); };
    void get_min2(Node *& first, Node * &second);
    void initialize(int arr[]);
    void get_huff_code(int index);
    void build_huff();
    int leaf;
    Node * tree;
    Node * root;
};

void HuffTree::initialize(int arr[])
{
    this->tree = new (Node[leaf * 2 - 1]);
    for (int i = 0; i < this->leaf; i++)
    {
        (this->tree[i]).weight = arr[i];
    }
}

void HuffTree::get_min2(Node * &first, Node * &second)
{
    first = second = NULL;
    int invalid = -1;
    for (int i = 0; i < leaf * 2 - 1; i++)
    {
        if (tree[i].parent != 0) continue;
        if (!first ? tree[i].weight>invalid:tree[i].weight >invalid && tree[i].weight < first->weight) first = &tree[i];
    }
    for (int i = 0; i < leaf * 2 - 1; i++)
    {
        if (tree[i].parent != 0||&tree[i] == first) continue;
        if (!second ? tree[i].weight>invalid:tree[i].weight >invalid && tree[i].weight < second->weight) second = &tree[i];
    }
}

void HuffTree::build_huff()
{
    for (int i = leaf; i < leaf * 2 - 1; i++)
    {
        Node *left, *right;
        get_min2(left, right);
        tree[i].weight = left->weight + right->weight;
        tree[i].left = left; tree[i].right = right;
        left->parent = right->parent = &tree[i];
    }
    root = &tree[leaf * 2 - 2];
}

void HuffTree::get_huff_code(int index)
{
    Node * parent, *current;
    char * code = new char[leaf + 1];
    int count = 0;
    for (current = &tree[index]; current->parent != NULL;current=parent)
    {
        parent = current->parent;
        if (parent->left == current) code[count++] = '0';
        else code[count++] = '1';
    }
    while (count > 0)
    {
        std::cout << code[--count];
    }
    delete []code;
}

int main()
{
    // A.B,C,D,E,F
    int array[] = { 3, 6, 1, 5, 8, 2 };
    HuffTree a(array, 6);
    for (int i = 0; i < 6; i++) a.get_huff_code(i), std::cout << endl;
}

 

posted @ 2017-05-25 15:43  HEIS老妖  阅读(187)  评论(0编辑  收藏  举报