Implement the greedy Heman tree strategy with the smallest priority queue
Use the smallest priority queue to store the key to be encoded and the internal nodes after merging. Note that the smallest priority queue will be deleted when the minimum value is obtained. The following is the java implementation.
Package Algorithms; class MinQueue
> {Int heapSize; T [] heap; int capacity; public MinQueue (int capaticty) {this. capacity = capaticty; heapSize = 0; // because of generic erasure, generics cannot be instantiated and only objects can be created, then forcibly convert the data type to an array. // The new Object cannot be used here. Because there is no comparable, use the direct parent class comparableheap = (T []) new Comparable [capaticty];}. /*** maintenance of the minimum priority queue */public void heapfy (int I) {if (I> = heapSize & I <0) {System. out. println ("node error to be maintained"); return;} int left = 2 * I + 1; int right = 2 * I + 2; int min = I; // find the minimum value of I and its two children if (left
= Capacity) {System. out. println ("The minimum priority queue is full! "); Return;} heap [heapSize] = ele; heapSize ++; int child = heapSize-1; int parent = (heapSize/2)-1; while (parent> = 0 & heap [parent]. compareTo (heap [child])> 1) {T temp = heap [parent]; heap [parent] = heap [child]; heap [child] = temp; child = parent; parent = (child + 1)/2-1 ;}} public T extractMin () {if (heapSize <= 0) {System. out. println ("No element"); return null;} T min = heap [0]; heapSize --; heap [0] = heap [heapSize]; heap [heapSize] = min; heapfy (0); return min;} public class HumanCode {public static class Node implements Comparable
{Public int freq; // occurrence frequency of characters: public char key; public Node left; public Node right; public Node (int freq, char key, Node left, Node right) {this. freq = freq; this. key = key; this. left = left; this. right = right ;}@ Overridepublic int compareTo (Node o) {if (this. freq> o. freq) return 1; else if (this. freq = o. freq) return 0; elsereturn-1;}/*** @ param q * construct a user-defined tree with n keywords to be merged n-1 times */public Node huffman (MinQueue
Q) {int n = q. heapSize; for (int I = 1; I
Q = new MinQueue
(6); Node node1 = new HumanCode. node (5, 'F', null, null); Node node2 = new HumanCode. node (9, 'E', null, null); Node node3 = new HumanCode. node (12, 'C', null, null); Node node4 = new HumanCode. node (13, 'B', null, null); Node node5 = new HumanCode. node (16, 'D', null, null); Node node6 = new HumanCode. node (45, 'A', null, null); q. insert (node1); q. insert (node2); q. insert (node3); q. insert (node4); q. insert (node5); q. insert (node6); Node node = hu. huffman (q); hu. huffmanAccess (node ,"");}}