如何在控制台中显示霍夫曼树?

时间:2012-03-16 04:53:10

标签: java huffman-code

很难解释所需的结果,但我在这里特别想要的只是典型树的输出,如果你向左转90度。

printTree(tree, "\t", 0);

private static void printTree(HTree tree, String space, int height) {
  assert tree != null;
  if (tree instanceof HLeaf) {
    HLeaf leaf = (HLeaf)tree;

    for (int k = 0; k < height; k++)
      System.out.print(space);
      System.out.println("(" + leaf.value + ")");      
    }

  else if (tree instanceof HNode) {
    HNode node = (HNode)tree;
    // traverse left
    printTree(node.left, space, height++);


    // traverse right

    printTree(node.right, space, height++);  
  }    
}

输出如下:

(e)
(s)
(o)
    (w)
    (l)
        (n)
        (t)
    (h)
        (k)
        ( )
        (a)

如您所见,这与霍夫曼树不太相似。

1 个答案:

答案 0 :(得分:3)

您可能需要查看this示例。霍夫曼树以下列方式印刷。

Display of Huffman coding tree



   +---f: 0.3960, 0 (step 6)
   |   
   +---@: 1.0000, 
   |   
   |       
   |           
   |               
   |           +---a: 0.0495, 1000 (step 2)
   |           |   
   |       +---+---@: 0.1089, 100 (step 3)
   |       |   |   
   |       |   |       
   |       |   |   +---#: 0.0099, 10010 (step 1)
   |       |   |   |   
   |       |   +---+---@: 0.0594, 1001 (step 2)
   |       |       |   
   |       |       +---b: 0.0495, 10011 (step 1)
   |       |           
   |       |       
   |       |   
   |   +---+---@: 0.2574, 10 (step 5)
   |   |   |   
   |   |   +---c: 0.1485, 101 (step 3)
   |   |       
   |   |   
   +---+---@: 0.6040, 1 (step 6)
       |   
       |       
       |   +---d: 0.1683, 110 (step 4)
       |   |   
       +---+---@: 0.3465, 11 (step 5)
           |   
           +---e: 0.1782, 111 (step 4)