很难解释期望的结果,但是我要在这里专门针对的是将树向左旋转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)


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

最佳答案

您可能想看一下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)

关于java - 如何在控制台中显示霍夫曼树?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9732086/

10-11 20:27