在哈夫曼树上搜索路径

发布于 2024-09-11 13:04:17 字数 96 浏览 2 评论 0原文

我正在研究霍夫曼树,我试图弄清楚如何遍历树以找到具有我正在寻找的字符的节点。在搜索树时,我需要使用 1 和 0(0 左 1 右)保留通往我正在查找的节点的路径字符串。我该怎么做?

I'm working on a Huffman tree and I'm trying to figure out how to traverse the tree to find the node that has the character that I'm looking for. While searching the tree i need to keep a string of the path that is taken to the node that I'm looking for using 1's and 0's (0 left 1 right). How can i do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

源来凯始玺欢你 2024-09-18 13:04:17

自从我写霍夫曼引擎以来已经很长时间了,但我会尝试一下。

伪代码。

假设你的霍夫曼树节点看起来像这样

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);

Long time since i wrote a huffman engine, but i'll give it a shot.

Pseudo Code.

Assuming your Huffman Tree Node looks like this

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

So here's recursive function (converting it to iterative should be easy)

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);
}

call it this way

buildCodes(rootHuffNode,0);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文