-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHuffmanTree.cs
58 lines (53 loc) · 2 KB
/
HuffmanTree.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Asgn
{
internal class HuffmanTree
{
private HuffmanNode root;
public HuffmanTree(IEnumerable<KeyValuePair<char, int>> counts)
{
var priorityQueue = new PriorityQueue<HuffmanNode>();
/*loop for kvp in counts and enqueues a new huffmantree node with its frequency */
foreach (KeyValuePair<char, int> kvp in counts)
{
priorityQueue.Enqueue(new HuffmanNode { Value = kvp.Key, Count = kvp.Value }, kvp.Value);
}
/* Dequeue the minimum frequencies node */
/*creat a new node and the two nodes are set as children for the new node*/
/*loop unit it gets the root node*/
while (priorityQueue.Count > 1)
{
HuffmanNode n1 = priorityQueue.Dequeue();
HuffmanNode n2 = priorityQueue.Dequeue();
var n3 = new HuffmanNode { Left = n1, Right = n2, Count = n1.Count + n2.Count };
n1.Parent = n3;
n2.Parent = n3;
priorityQueue.Enqueue(n3, n3.Count);
}
root = priorityQueue.Dequeue();
}
/*construct a binary representation of the path, it assigns left and right with '0' and '1' respectively */
private void Encode(HuffmanNode node, string path, IDictionary<char, string> encodings)
{
if (node.Left != null)
{
Encode(node.Left, path + "0", encodings);
Encode(node.Right, path + "1", encodings);
}
else
{
encodings.Add(node.Value, path);
}
}
/* create a dictionary that the symbol is the key */
public IDictionary<char, string> CreateEncodings()
{
var encodings = new Dictionary<char, string>();
Encode(root, "", encodings);
return encodings;
}
}
}