Data structure-the Heman tree and Its Application

Source: Internet
Author: User

------ Storage representation of the Heman tree and Heman encoding ------ [cpp] typedef struct {unsigned int weight; unsigned int parent, lchild, rchild;} HTNode, * HuffmanTree; typedef char ** HuffmanCode; void HuffmanCoding (HuffmanTree & HT, HuffmanCode & HC, int * w, int n) {if (n <1) return; \ int m = 2 * n + 1; HT = (HuffmanTree) malloc (m + 1) * sizeof (HTNode); // units 0 are not used for (HuffmanTree p = HT; I = 1; I <= n; ++ I; ++ p; ++ w) * p = {* w, 0, 0, 0}; for (; I <= M; ++ I; ++ p) * p = {0, 0, 0}; for (I = n + 1; I <= m; I ++) {// create HuffmanTree Select (HT, I-1, s1, s2); HT [s1]. parent = I; HT [s2]. parent = I; HT [I]. lchild = s1; HT [I]. rchild = s2; HT [I]. weight = HT [s1]. weight + HT [s2]. weight;} HC = (HuffmanCode) malloc (n + 1) * sizeof (char *); cd = (char *) malloc (n * sizeof (char )); cd [n-1] = "\ 0"; for (I = 1; I <= n; I ++) {int start = n-1; for (c = I, f = HT [I]. parent; f! = 0; c = f; f = HT [f]. parent) if (HT [f]. lchild = c) cd [-- start] = "0"; else cd [-- start] = "1"; HC [I] = (char *) malloc (n-start) * sizeof (char); strcyp (HC [I], & cd [start]);} free (cd );} ------ non-recursive traversal of the Heman tree without stacks, and request the Heman encoding ------ [cpp] HC = (HuffmanCode) malloc (n + 1) * sizeof (char *)); int p = m, cdlen = 0; for (int I = 1; I <= m; ++ I) HT [I]. weight = 0; while (p) {if (HT [p]. weight = 0) {HT [p]. weight = 1; if (HT [p]. lchild! = 0) {p = HT [p]. lchild; cd [cdlen ++] = "0";} else if (HT [p]. lchild = 0) {HC [p] = (char *) malloc (cdlen + 1) * sizeof (char); cd [cdlen] = "\ 0 "; www.2cto.com strcpy (HC [p], cd) ;}} else if (HP [p]. weight = 1) {HT [p]. weight = 2; if (HT [p]. rchild! = 0) {p = HT [p]. rchild; cd [cdlen ++] = "1";} else {HT [p]. weight = 0; p = HT [p]. parent; -- cdlen ;}}}

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.