(Heap application) Establishment of the Huffman

Source: Internet
Author: User

Future correction

Recently, I found that my code has a problem. I also found it only when I was doing another experiment on Hamman. Many times in the code, I used new to create a new node, this includes extracting the node with the minimum weight from the minimum heap (this is not an error), generating a new node based on the two minimum weight nodes, and inserting the new node into the minimum heap. The problem lies in the last two, because in the middle step, we set the parent for left and right (it should be clear after reading my code ), in fact, it is very complicated to proceed like this, because it is very easy to confuse new with new and assign values.

After a test, some children's (left or right) parent pointers will be wrong. So today, I updated the Huffman Harman code.It is also worth mentioning that I have read a lot of similar code on the Internet and found many errors, and the most important errors are here.


The basic idea of building a Huffman tree is to specify a series of data with weights (with weights) and select two data with minimum weights to form a tree. The obtained parent node is then inserted into the data series.

At the beginning, according to Yan's method, the Huffman tree was created using the sequence table. Similarly, during the creation process, we should select a small number from the sequence table, after adding, insert it to the end of the table until all given points are inserted. It is also flexible and convenient to build with the minimal heap. The Heap has high performance and the sorting time complexity is nlog (2) n. Using the smallest heap, we can quickly find the smallest element (always on the top ).

 

In the following 8 steps, we will immediately master the use of the minimum heap to build the Huffman tree.

View illustration

① Source image (already the smallest heap );

② Swap the first element of the SWAp heap (the weight must be the smallest) with the last element;

③ Deleting the last element after the switch (copied) is not a real deletion, but a size-1 operation. After the switch, it is not a heap, re-adjust the heap to the minimum heap. You can call the heap recursively or use the subscript as the judgment condition. My Code uses the subscript judgment condition;

④ Continue ②;

⑤ Adjust with the smallest weight. Copy the two smallest points of weight to form a new parent node and adjust the internal pointer relationship between them;

⑥ After adjustment;

7. insert and adjust new nodes;

After renewal is adjusted.

 

 

After the first operation, continue to know that only the last element is left in the heap, and then point the root element to it. below is the code. In this case, the Huffman tree is built.

PS: when the following code creates a minimum heap and obtains the Huffman node with the minimum weight in the heap, weight (weight) is not added to the huffmannode design process ), therefore, the data (INT type) value is used as the weight.


Data Structure Design of the Huffman node:

# Ifndef _ huffmannode_h _ # DEFINE _ huffmannode_h_struct huffmannode // Huffman node definition {PRIVATE: int data; public: // constructor huffmannode * left, * right, * parent; huffmannode (): Left (null), right (null), parent (null), data (-1) {} huffmannode (int d): Left (null), right (null ), parent (null), data (d) {}// overload operator huffmannode & operator = (const huffmannode & HN) {left = hn. left; Right = hn. right; Data = hn. data; return * This;} // data acquisition and maintenance int getdata () const {return data;} // get data bool setdata (INT d) {DATA = D; return true;} // set data}; # endif

Minimum heap class:

# Include <iostream> using namespace STD; # ifndef _ minheap_h _ # DEFINE _ minheap_h _ # include "huffmannode. H "const int defaultsize = 100; Class minheap {huffmannode * heap; int szcurrent; public: minheap (int sz = defaultsize );~ Minheap () {Delete [] heap;} void createminheap (INT arr [], int N); // The minimum heap bool insert (huffmannode * E) of array construction ); // Insert the Huffman node void siftdown (INT start, int m) into the heap; // slide down and reconstruct the smallest heap void siftup (INT start, int m); // slide up, use huffmannode * getminnode () when inserting; // obtain the node with the smallest data value of the Huffman node, and maintain szcurrentbool swapnode (int I, Int J ); // switch the Huffman node void print () with the subscript I and j; // print the Huffman node}; # endif # include <iostream> using namespace STD; # include "minheap. H "# include <assert. h> minheap: minheap (INT sz) {heap = new huffmannode [SZ]; Assert (heap! = NULL); szcurrent = 0;} void minheap: createminheap (INT arr [], int N) {This-> heap = new huffmannode [defaultsize]; Assert (heap! = NULL); int I; for (I = 0; I <n; I ++) Heap [I]. setdata (ARR [I]); szcurrent = N; int currentpos = (szCurrent-2)/2; // Adjust while (currentpos> = 0) from the last Vertex) {siftdown (currentpos, szCurrent-1); currentpos -- ;}} void minheap: siftdown (INT start, int m) {int I = start, j = I * 2 + 1; huffmannode temp = heap [I]; while (j <= m) {If (j <M & heap [J]. getdata ()> heap [J + 1]. getdata () // J records smaller subnodes J ++; If (temp. getdata () <= heap [J]. getdata () // do not adjust the break; else {heap [I] = heap [J]; // move the child node up to I = J; j = 2 * j + 1 ;}} heap [I] = temp;} void minheap: siftup (INT start, int m) {Int J = start, // subnode position I = (START-1)/2; // The vertex position huffmannode temp = heap [J]; // record the subnode while (j> 0) {If (temp. getdata ()> heap [I]. getdata () // do not adjust break; else {heap [J] = heap [I]; // vertex slide J = I; I = (I-1)/2 ;}} heap [J] = temp;} void minheap: Print () {for (INT I = 0; I <szcurrent; I ++) cout 

Huffman class:

# Include "minheap. H "# ifndef _ huffmantree_h _ # DEFINE _ huffmantree_h_class Huffman {minheap * MH; // heap to help build the Huffman tree huffmannode * root; // The root node of the Huffman tree public: huffman (): Root (null ){};~ Huffman () {Delete MH; makeempty (Root);} void makeempty (huffmannode * PTR) {If (PTR-> left) makeempty (PTR-> left ); if (PTR-> right) makeempty (PTR-> right); Delete PTR;} void createhuffmantree (INT arr [], int size); void print (); void adjust (huffmannode * PTR) ;};# endif # include <iostream> using namespace STD; # include <assert. h> # include "huffmantree. H "# include" minheap. H "# include <queue> void Huffman: createhuffmantree (int Arr [], int size) {MH = new minheap (size); MH-> createminheap (ARR, size); // create the minimum heap int I for data; huffmannode * left; huffmannode * right; huffmannode * parent; for (I = 0; I <size-1; I ++) {left = MH-> getminnode (); // relatively small to left Child Right = MH-> getminnode (); // relatively large to right child // here we can come up with a function, but it is a little troublesome, straight view parent = new huffmannode (left-> getdata () + right-> getdata (); parent-> left = left; parent-> right = right; left-> parent = right-> parent = parent; I F (! Mh-> insert (parent) Abort (); cout <"heap after the parent node is inserted:"; MH-> Print ();} root = parent ;} void Huffman: Print () {queue 

 

Huffman (Huffman) is widely used in the field of communication and also has some application in File compression technology. It will be useful in the future and will be shared with you. Welcome to discuss it :).

Troublemakers 2011-12-15

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.