while (listpc.Count > 1) {
Node n = new Node();
n.prioirry = listpc[0].prioirry + listpc[1].prioirry; n.lchild = listpc[0]; n.rchild = listpc[1]; listpc.RemoveAt(0); listpc.RemoveAt(0); int index = -1;
for (int i = 0; i < listpc.Count; i++) {
if (n.prioirry <= listpc[i].prioirry) {
index = i; break; } }
if (index == -1) {
index = listpc.Count; }
listpc.Insert(index, n); }
string encodestr = \; viewTree(listpc[0], \); huffTree = listpc[0];
for (int i = 0; i < str.Length; i++) {
encodestr += dictcode[str[i]]; }
return encodestr; }
private void viewTree(Node n, string v) {
if (n.code != '\\0') {
dictcode.Add(n.code, v); } else {
if (n.lchild != null) {
string vl = v + \; viewTree(n.lchild, vl); }
if (n.rchild != null) {
string vr = v + \; viewTree(n.rchild, vr); } } }
private string decode(string str) {
Node root = huffTree; string result = \;
for (int i = 0; i < str.Length; i++) {
if (root.code != '\\0') {
result += root.code.ToString(); root = huffTree; }
if (str[i] == '0') {
root = root.lchild; } else {
root = root.rchild; } }
if (root.code != '\\0') {
result += root.code.ToString(); }
return result; }
private void button1_Click_1(object sender, EventArgs e) {
textBox2.Text = encode(textBox1.Text); }
private void button2_Click_1(object sender, EventArgs e) {
textBox3.Text = decode(textBox2.Text); }
private void button3_Click(object sender, EventArgs e) {
this.Close(); }
private void button4_Click(object sender, EventArgs e) {
textBox1.Text = \; textBox2.Text = \; textBox3.Text = \; } }
}
4) 测试过程:
1. 输入任意数据,选择编码,输出结果Huffman编码
2. 输入刚才的Huffman编码,选择解码,则解码结果为原始数据
3. 测试完成。