簡體   English   中英

在霍夫曼樹上搜索路徑

[英]Searching for the path on a Huffman Tree

我正在研究霍夫曼樹,並且試圖找出如何遍歷樹以找到具有我要尋找的角色的節點。 在搜索樹時,我需要使用1和0(0左1右)保留要查找的節點的路徑字符串。 我怎樣才能做到這一點?

自從我寫了一個霍夫曼引擎以來已經有很長時間了,但是我會給它一個機會。

偽代碼。

假設您的霍夫曼樹節點看起來像這樣

class HuffNode
{
...
char ch;
long huffCode; //initialized to zero initially
HuffNode left,right;
}

所以這是遞歸函數(將其轉換為迭代應該很容易)

void buildCodes(HuffNode currentNode, long currentCode)
{
currentNode->huffCode =  currentCode;
if(currentNode->left != null) buildCodes(currentNode->left, currentCode << 1);
if(currentNode->right != null) buildCodes(currentNode->right, (currentCode << 1) | 1);
}

這樣稱呼

buildCodes(rootHuffNode,0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM