因此,我处理的树的compareTo()方法的计算结果通常相同,但我需要在PriorityQueue中的现有节点之前插入新的树。现在,PriorityQueue的java实现似乎将新节点放置在类似节点的随机位置。
while (pq.size() >= 2) {
System.out.println("Iteration: " + i++);
printPQ();
BinaryTree b1 = pq.remove();
BinaryTree b2 = pq.remove();
BinaryTree newTree = new BinaryTree(b1, b2);
//add the newly created tree back into pq
pq.add(newTree);
System.out.println();
}
对于那些想知道的人来说,这是一个霍夫曼代码的实现。
您可以修改compareTo(...)
方法。如果将创建时间作为属性添加到BinaryTree
,则可以将其包含在比较中,并确保PriorityQueue
中新添加元素的顺序。