Java霍夫曼树

时间:2015-11-17 03:17:09

标签: java tree huffman-code

我试图实现打印一个霍夫曼树,但代码代表(1s和0s)。到目前为止,我有这个,但它并没有做我想要的。我可以打印一棵树,但没有代码。输入是频率表。

我希望输出是二叉树(格式化,但它不需要完美)和每个符号的霍夫曼代码本身。

我有另一种打印代码的方法,但是我不能让它在我想要的上下文中工作。这是树打印代码:

Stream<Map.Entry>

以下是生成1和0的代码:

import java.util.*;

public class Node implements Comparable<Node> {

    Node left;
    Node right;
    Node parent;
    char text;
    int frequency;

    public Node(char 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);
        } 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[], char 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 void traverseDepthFirst(Node node, String code) {
    // only proceed if tree is not null
    if (node != null) {
        // compute the index of the symbol in S
        int index = 0;
        for (int i = 1; i <= n; i++) {
            if (S[i] == node.text) {
                index = i;
                break;
            }
        }
        // store the current code in the code array at the index of the
        // symbol
        this.code[index] = code;
        // traverse left
        this.traverseDepthFirst(node.left, code + "1");
        // traverse right
        this.traverseDepthFirst(node.right, code + "0");
    }
}

0 个答案:

没有答案