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....
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....

Leave a comment