File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
src/main/java/com/thealgorithms/greedyalgorithms Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .thealgorithms .greedyalgorithms ;
2+
3+ import java .util .PriorityQueue ;
4+
5+ /**
6+ * Huffman Coding Algorithm
7+ * Greedy algorithm used for optimal prefix codes.
8+ */
9+ public class HuffmanCoding {
10+
11+ static class Node implements Comparable <Node > {
12+ char character ;
13+ int frequency ;
14+ Node left ;
15+ Node right ;
16+
17+ Node (char character , int frequency ) {
18+ this .character = character ;
19+ this .frequency = frequency ;
20+ }
21+
22+ public int compareTo (Node other ) {
23+ return this .frequency - other .frequency ;
24+ }
25+ }
26+
27+ public static Node buildHuffmanTree (char [] chars , int [] freq ) {
28+ PriorityQueue <Node > pq = new PriorityQueue <>();
29+
30+ for (int i = 0 ; i < chars .length ; i ++) {
31+ pq .add (new Node (chars [i ], freq [i ]));
32+ }
33+
34+ while (pq .size () > 1 ) {
35+ Node left = pq .poll ();
36+ Node right = pq .poll ();
37+
38+ Node parent = new Node ('\0' , left .frequency + right .frequency );
39+ parent .left = left ;
40+ parent .right = right ;
41+
42+ pq .add (parent );
43+ }
44+
45+ return pq .poll ();
46+ }
47+ }
You can’t perform that action at this time.
0 commit comments