------ 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 ;}}}