Huffman Tree Realization

Source: Internet
Author: User

#include <iostream> #include <cstdio> #define INF 1<<30using namespace std;//Huffman tree Implementation// Huffman Tree Features: If there are n leaf nodes, then the sum of points is 2*n-1.      The more frequently the code accesses the shorter the struct node{int parent, Lson, Rson;int Val; Number of visits};void createtree (node p[], int n, int total)//total=2*n-1{for (int t=0; t<total; ++t)//Initialize {p[t].parent = P[t ].lson = P[t].rson =-1;}   for (int i=n; i<total; ++i) {int min1, min2, L, R; The maximum and the second largest value min1 = min2 = Inf;l = r = -1;for (int t=0; t<i; ++t)//traversal looks for two smallest points, which is the {if (p[t].parent =-1 Al<min1) {r = l;l = t;min2 = Min1;min1 = P[t].val;} else if (p[t].val<min2) {r = t;min2 = P[t].val;}}} P[i].val = min1 + min2;p[l].parent = p[r].parent = I;p[i].lson = L;p[i].rson = r;}} struct Code{int K;char c[100];}; void Huffmancode (node p[], int n, code c1[]) {for (int t=0; t<n; ++t) {int pre = P[t].parent;int g = t;c1[t].k = 0;while (P Re! =-1) {if (P[pre].lson = = g) {c1[t].c[c1[t].k++] = ' 0 ';} else {c1[t].c[c1[t].k++] = ' 1 ';} G = Pre;pre = P[pre].parent;} c1[t].k--;}} int main () {nOde p[4*2-1];for (int t=0; t<4; ++t) {p[t].val = 2*t+1;} Createtree (P, 4, 2*4-1); Code C[4];huffmancode (P, 4, c); for (int t=0; t<4; ++t) {int k = c[t].k;printf ("%d:", p[t].val); fo R (int j=k; j>=0;--j) {printf ("%c", C[t].c[j]);} printf ("\ n");} return 0;}


Operation Result:



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Huffman Tree Realization

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.