5

我试图了解如何处理我的作业问题。我正在尝试创建一个将在 Java 中编码和解码消息的霍夫曼树。我得到了字符串和频率。

[a=10, b=15, c=12, e=3, nl=4, sp=13, t=1]. 

我知道使用霍夫曼树,您可以将两个最低频率并将它们制成一棵树,并将它们的频率之和作为父级。我知道使用优先队列我可以将所有频率插入其中并使用该remove()方法取出 2 个最低频率。然后将它们加在一起以获得它们的权重,然后将该权重插入队列并重复。

最后一棵树的重量应为

[58=root, root.left = 33, root.right = 25]   
[33.left = 18,  18.left = 8,  8.left = 4] 

我不确定如何开始实现霍夫曼树代码,该代码将能够创建具有频率的树并显示树。我查看了其他代码,似乎它们都是从 Streaming Input Code 左右创建的。

任何帮助都会让我继续前进。提前致谢!

我想用如下格式打印出来:(预购遍历)

58  
- 33  
- - 18  
- - - 8  
- - - - 4  
- - - - - 1:t  
- - - - - 3:e  
- - - -  4:nl  
- - - 10:a  
- - 15:b  
- 25  
- - 12:c  
- - 13:sp  
4

1 回答 1

4
import java.util.PriorityQueue;

public class Node implements Comparable<Node> {
    Node left;
    Node right;
    Node parent;
    String text;
    int frequency;

    public Node(String textIn, int frequencyIn) {
        text = textIn;
        frequency = frequencyIn;
    }

    public Node(int frequencyIn) {
        text = "";
        frequency = frequencyIn;
    }

    public int compareTo(Node n) {
        if (frequency < n.frequency) {
            return -1;
        }
        else if(frequency > n.frequency) {
            return 1;
        }
        return 0;
    }

    public static void printFromPreOrder(Node n, String dashes) {
        // print with colon if leaf node
        if (n.text != "") {
            System.out.println(dashes + n.frequency + ":" + n.text);
        }
        else {
            System.out.println(dashes + n.frequency);
        }

        // Start recursive on left child then right
        if (n.left != null) {
            printFromPreOrder(n.left, dashes + "-");
        }
        if (n.right != null) {
            printFromPreOrder(n.right, dashes + "-");
        }
    }

    // Returns root node to pass to printFromPreOrder
    public static Node makeHuffmanTree(int frequencies[], String text[]) {
        PriorityQueue<Node> queue = new PriorityQueue<Node>();
        for (int i = 0; i < text.length; i++) {
            Node n = new Node(text[i], frequencies[i]);
            queue.add(n);
        }
        Node root = null;
        while (queue.size() > 1)  {
            Node least1 = queue.poll();
            Node least2 = queue.poll();
            Node combined = new Node(least1.frequency + least2.frequency);
            combined.right = least1;
            combined.left = least2;
            least1.parent = combined;
            least2.parent = combined;
            queue.add(combined);
            // Keep track until we actually find the root
            root = combined;
        }
        return root;
    }

    public static void main(String[] args) {
        int frequencies[] = {10, 15, 12, 3, 4, 13, 1};
        String text[] = {"a", "b", "c", "e", "nl", "sp", "t"};
        Node root = Node.makeHuffmanTree(frequencies, text);
        Node.printFromPreOrder(root, "");
    }
}

这对你有用。我已经包含了您的示例,但它应该适用于任意数量的频率和文本。只要确保频率和文本大小相同,因为我没有进行错误检查。

于 2013-03-31T23:40:03.983 回答