2012-03-16 85 views
0

这是很难解释所需的结果,但我在这里特意找到的只是你的典型树的输出,如果你把它转向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) 

正如你所看到的,并不像霍夫曼树非常好。

回答

3

你可能想看看this的例子。霍夫曼树按以下方式打印。

Display of Huffman coding tree 



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