我在霍夫曼编码Java中遇到逻辑错误

问题描述 投票:0回答:1

这里是代码...

public class Huffman_Coding {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string to compress: ");
        String str = sc.nextLine();
        sc.close();
        HashString hs = new HashString();

        HashMap<Character, Integer> hm = hs.getStringHash(str);

        PriorityQueue<Node> pq = new PriorityQueue<Node>();
        for (char ch : hm.keySet()) {
            pq.add(new Node(null, null, hm.get(ch), ch));
        }
        System.out.println(pq);
        while (pq.size() != 1) {
            Node left = pq.poll();
            Node right = pq.poll();
            Node parent = new Node(left, right, left.freq + right.freq, '\0');
            pq.add(parent);
            System.out.println(pq);
        }
        Huffman_Tree ht = new Huffman_Tree();
        String ans = "";
        ht.inOrder(pq.poll(), ans);
    }
}

class Node implements Comparable<Node> {

    @Override
    public String toString() {
        return "Node [freq=" + freq + ", ch=" + ch + "]";
    }

    Node lptr;
    Node rptr;
    int freq;
    char ch;

    Node(Node lptr, Node rptr, int freq, char ch) {
        this.freq = freq;
        this.lptr = lptr;
        this.rptr = rptr;
        this.ch = ch;
    }

    public int compareTo(Node o) {

        int comparedvalue = Integer.compare(this.freq, o.freq);
        if (comparedvalue != 0)
            return comparedvalue;
        else
            return Integer.compare(this.ch, o.ch);
        }
    }

    boolean isLeaf() {
        return this.lptr == null && this.rptr == null;
    }
}

class Huffman_Tree {
    void inOrder(Node root, String code) {
        if (!root.isLeaf()) {
            inOrder(root.lptr, code + '0');
            inOrder(root.rptr, code + '1');

        } else
            System.out.println(root.ch + " : " + code);

    }
}

这里,对于输入字符串abccddeeee,我得到类似的东西:

[Node [freq=1, ch=a], Node [freq=1, ch=b], Node [freq=2, ch=c], Node [freq=2, ch=d], Node [freq=4, ch=e]]
[Node [freq=2, ch= ]]

我很困惑,为什么在第二步中,具有'd'的节点要从'e'开始。这使我在最终编码中出错。为什么compareTo方法失败,我无法理解。

getHashString返回一个哈希,该哈希在键中包含字符,在值中包含其频率。

java huffman-code
1个回答
0
投票

我不知道为什么在[[polling元素ant adding新的“ synthetic”元素之后PriorityQueue中元素的顺序为什么不是期望的顺序,但是我认为您可以解决问题切换到TreeSet,就像我用[]成功完成的TreeSet<Node> pq = new TreeSet<Node>((n1, n2) -> n1.compareTo(n2)); // explicit but unnecessary comparator

并将每个pq.poll()调用更改为pq.pollFirst() ...

我希望此解决方法可以为您提供帮助!

© www.soinside.com 2019 - 2024. All rights reserved.