Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Huffman Encoding Tree
/** * Huffman Encoding Tree * * Author: Jayesh Chandrapal * Version: 1.0 */ import java.util.*; import java.lang.*; import java.io.*; class Node implements Comparable<Node> { Character character; Integer frequency; Node left; Node right; Node(Character character, Integer frequency) { this.character = character; this.frequency = frequency; } @Override public int compareTo(Node otherNode) { return this.frequency.compareTo(otherNode.frequency); } @Override public String toString() { return "[ " + character + " : " + frequency + " ]"; } } class Rextester { Map<Character, Integer> characterMap; PriorityQueue<Node> tree; Rextester() { characterMap = new LinkedHashMap<Character, Integer>(); characterMap.put('a', 5); characterMap.put('b', 9); characterMap.put('c', 12); characterMap.put('d', 13); characterMap.put('e', 16); characterMap.put('f', 45); tree = new PriorityQueue<Node>(); } public static void main (String[] args) throws java.lang.Exception { Rextester app = new Rextester(); app.buildTree(); app.displayQueue(); System.out.println("done"); } public void buildTree() { for(Map.Entry<Character, Integer> entry : characterMap.entrySet()) { tree.add(new Node(entry.getKey(), entry.getValue())); } while(tree.size() > 1) { Node node1 = tree.poll(); Node node2 = tree.poll(); Node newNode = new Node('*', node1.frequency + node2.frequency); newNode.left = node1; newNode.right = node2; tree.add(newNode); } // One remaining node is the root of final tree Node finalTree = tree.poll(); displayTree(finalTree); } public void displayTree(Node root) { if(root != null) System.out.println(root); if(root.left != null) displayTree(root.left); if(root.right != null) displayTree(root.right); } public void displayQueue() { for(Node node : tree) { System.out.println(node); } } }
run
|
edit
|
history
|
help
0
Le saviez-vous ?
Complex Number implementation using oops java
Reverse a Linked List in groups of given size k
http://stackoverflow.com/questions/23175927/how-to-clone-object-defined-by-interface
a+b
3.E
Abhay
Sort arraylist bubble sort
Borrowing class
// Java Coding Challenge - 07: Print out Fibonacci number 0 - 1000