Greedy Huffman tree

Source: Internet
Author: User

The greedy idea is very simple. The key lies in what structure is used to implement the greedy process.

Package section9;

Import java. util. Queue;
Import java. util. iterator;
Import java. util. Collections list;


/* Chapter 9 greedy algorithm Huffman encoding */

Public class Huffman {

/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
// Todo auto-generated method stub
Double [] P = {0.35, 0.1, 0.2, 0.2, 0.15 };
Char [] cc = {'B', '-', 'C', 'D', 'A '};

Treenode root = Huffman (p, CC );

System. Out. println (root. P );
}


Public static treenode Huffman (double [] P, char [] CC ){
// Input the probability array of characters to be encoded and return the root node of the Huffman tree
Int n = P. length;
Treenode [] Roots = new treenode [N]; // array of the current Root Node
Queue <treenode> queue = new queue list <treenode> (); // note that in Java, queue is an interface.

// Tree queue Initialization
For (INT I = 0; I <n; I ++)
{
Roots [I] = new treenode (P [I]);
Roots [I]. c = Cc [I];
Queue. Add (roots [I]);
}

While (queue. Size ()! = 1)
{
// Locate and delete the smallest Node
Treenode leftnode = queue. Peek ();
Iterator it = queue. iterator ();
While (it. hasnext ())
{
Treenode node = (treenode) it. Next ();
If (node. P <leftnode. p)
Leftnode = node;
}
Queue. Remove (leftnode );

// Locate and delete the smallest Node
Treenode rightnode = queue. Peek ();
It = queue. iterator ();
While (it. hasnext ())
{
Treenode node = (treenode) it. Next ();
If (node. P <rightnode. p)
Rightnode = node;
}
Queue. Remove (rightnode );

// Construct a tree with the smallest two nodes and add it to the tree queue
Treenode root = new treenode (leftnode. P + rightnode. P );
Root. leftnode = leftnode;
Root. rightnode = rightnode;

Queue. Add (Root );
}

Return queue. Peek ();
}
}

Description omitted.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.