数据结构—哈夫曼树
原理:参考趣学数据结构
代码:
# include <stdio.h>
# include <stdlib.h>
# define N 100
# define INF 2 ^ 31 - 1
typedef struct fNode { int c; int parent; int lchild, rchild; int weight;
} fNode;
typedef struct rNode { int r[ N] ; int start; int length;
} rNode;
void huffMan ( fNode fnode[ ] , int n) { for ( int i = 0 ; i < n - 1 ; i++ ) { int min1= INF, min2 = INF; int u = - 1 , v = - 1 ; for ( int j = 0 ; j < n + i; j++ ) { if ( fnode[ j] . weight < min1 && fnode[ j] . parent== - 1 ) { min2 = min1; v = u; min1 = fnode[ j] . weight; u = j; } else if ( fnode[ j] . weight< min2 && fnode[ j] . parent == - 1 ) { min2 = fnode[ j] . weight; v = j; } } fnode[ n + i] . weight = min1 + min2; fnode[ n + i] . lchild = u; fnode[ n + i] . rchild = v; fnode[ u] . parent = fnode[ v] . parent = n + i; }
}
void findHuffManCodePath ( fNode fnode[ ] , rNode rnode[ ] , int n) { rNode temp; int start= n- 1 ; for ( int i = 0 ; i < n; i++ ) { start = n - 1 ; int p = fnode[ i] . parent; int tempv = i; while ( p != - 1 ) { if ( tempv == fnode[ p] . lchild) { temp. r[ start] = 0 ; } else { temp. r[ start] = 1 ; } start-- ; tempv = p; p = fnode[ p] . parent; } for ( int j = start + 1 ; j <= n - 1 ; j++ ) { rnode[ i] . r[ j] = temp. r[ j] ; rnode[ i] . start = start + 1 ; } rnode[ i] . length = n - start - 1 ; } int sum = 0 ; for ( int j = 0 ; j < n; j++ ) { printf ( "%d的哈夫曼编码为:" , fnode[ j] . c) ; for ( int k = rnode[ j] . start; k <= n - 1 ; k++ ) { printf ( "%d" , rnode[ j] . r[ k] ) ; } sum += ( fnode[ j] . weight* rnode[ j] . length) ; printf ( " " ) ; } printf ( "\n" ) ; printf ( "哈夫曼编码长度为:%d\n" , sum) ; printf ( "\n" ) ;
}
int main ( ) { fNode fnode[ N] ; rNode rnode[ N] ; int u; printf ( "请输入编码字符的个数:" ) ; scanf_s ( "%d" , & u) ; int length = u; int c; int weight= 0 ; for ( int k = 0 ; k < u; k++ ) { scanf_s ( "%d %d" , & c, & weight) ; fnode[ k] . c = c; fnode[ k] . weight = weight; } u = 2 * length - 1 ; for ( int i= 0 ; i< u; i++ ) { fnode[ i] . lchild = - 1 ; fnode[ i] . rchild = - 1 ; fnode[ i] . parent = - 1 ; } huffMan ( fnode, length) ; findHuffManCodePath ( fnode, rnode, length) ; system ( "pause" ) ; return 0 ;
}
测试截图:
时间复杂度O(n x n),空间复杂度O(n)
如果存在什么问题,欢迎批评指正!谢谢!