【问题标题】:Searching for the path on a Huffman Tree在霍夫曼树上搜索路径
【发布时间】:2010-11-13 13:02:37
【问题描述】:

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

【问题讨论】:

    标签: java tree huffman-code traversal


    【解决方案1】:

    很久没有写哈夫曼引擎了,但我会试一试。

    伪代码。

    假设您的 Huffman 树节点如下所示

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多