Huffman tree and map

| No Comments | No TrackBacks
I was doing a little coding on my school's work, it's about Huffman code, I just think that it is very useful, and I was having a little issue of retrieving data correctly from the huffman tree. So I figure I just post the code here, in case some one else is gonna need it.

Method 1: search the Huffman Tree every time to get the code

// this function take "temp"as a temporary variable to store the code string
// aChar is char we are looking for in the tree
// tree is the Huffman tree we built
// the function will return the huffman code for this character

string findHuffCode(string temp,const char& aChar,const HuffTreeNode* tree)
{
    if (tree->IsLeaf())
    {
        if (tree->Value.Symbol==aChar)
            return temp;
        else
            return "";
    }
    else
    {
        if (findHuffCode(temp+"0",aChar,tree->Left)=="")
            return findHuffCode(temp+"1",aChar,tree->Right);
        else
            return findHuffCode(temp+"0",aChar,tree->Left);
    }
}

Method 2: using a map structure to store the Huffman code for every character

// huffMap is the map we will build
// temp is the temp string store the Huffman code
// tree is the Huffman tree we built
void buildHuffMap(map<char,string>& huffMap,string temp,const HuffTreeNode* tree)
{
    if (tree->IsLeaf())
    {
        huffMap[tree->Value.Symbol]=temp;
    }
    else
    {
        buildHuffMap(huffMap,temp+"1",tree->Right);
        buildHuffMap(huffMap,temp+"0",tree->Left);
    }
}

tree structure is the most useful data structure that I v seen, and recursion is the most magical process I v known....

No TrackBacks

TrackBack URL: https://blogs.psu.edu/mt4/mt-tb.cgi/60135

Leave a comment

About this Entry

This page contains a single entry by HUAIDONG WANG published on April 12, 2009 9:55 PM.

plans for the next few months was the previous entry in this blog.

SimpleRace v1.04 test version is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Subscribe

Powered by Movable Type 4.23-en