|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 t6am3 于 2018-3-2 10:15 编辑
编译环境VC6.0
今天在B站上看小甲鱼老师的数据结构及算法教程,学习到霍夫曼树的建立,于是先暂停视频想自己先编一下
编完之后 调试发现 创建霍夫曼树的函数已经返回了一棵完整的霍夫曼树 过程如图:
在遍历函数中调用还是完整的
我怀疑是VC6.0编译器的问题 因为以前也出现过好几次这种情况就是单步调试的时候发现不可能变值的地方值变了。。。
附上我的代码:另外本人纯属新手,代码冗杂,欢迎教导,感谢各位大佬的帮助!!!
#include <stdio.h>
#include <stdlib.h>
//#include <time.h>
// For BTREE;
#define MAX_SIZE 20
struct BTREE
{
int data;
struct BTREE *leftchild;
struct BTREE *rightchild;
};
struct Cmp
{
int data;
int tag;
};
void print_preorder_recursion( struct BTREE *x )
{
printf("%d ", x->data);
if( NULL != x->leftchild )
print_preorder_recursion( x->leftchild );
if( NULL != x->rightchild )
print_preorder_recursion( x->rightchild );
}
void Insert( struct Cmp *p, struct Cmp *t, int n )
{
int i = 0;
while( (p + i)->data < t->data && i < n )
{
i++;
}
for( ; i > 0; i-- )
{
*(p-1) = *p;
p++;
}
*(p-1) = *t;
}
void swap( struct Cmp *a, struct Cmp *b )
{
struct Cmp tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
void Sort( struct Cmp *p, int n )
{
int i, j;
for( i = 1; i < n; i++ )
for( j = i ; j >= 0; j-- )
{
if( p[j].data < p[j-1].data )
swap( &p[j], &p[j-1] );
}
}
struct BTREE *Huffman_Generate( struct BTREE *p, int n )
{
struct BTREE *t;
int i, h = n, m = n;
struct Cmp Tag[MAX_SIZE], tmp, *g;
for( i = 0; i < n; i++ )
{
Tag[i].data = p[i].data;
Tag[i].tag = i;
}
Sort( Tag, n );
g = Tag;
while( 1 )
{
t = (struct BTREE *)malloc(sizeof(struct BTREE));
t->data = (p+g->tag)->data + (p+(g+1)->tag)->data;
t->leftchild = p+g->tag;
g++;
h--;
t->rightchild = p+g->tag;
g++;
h--;
tmp.data = t->data;
tmp.tag = m++;
p[tmp.tag] = *t;
Insert( g, &tmp, h );//zuihouyici charu de shihou youwenti ..qing xiugai charu hanshu yiji h de zhi youdaishangque.
g--;
h++;
if( 1 == h )
break;
}
return t;
}
struct BTREE *Huffman()
{
int i, n;
struct BTREE node[MAX_SIZE];
printf("Plz input the nodes you possess:\n");
scanf("%d", &n);
for( i = 0; i < n; i++ )
{
printf("Plz input %d weight of the node:\n", i+1);
//getchar();
scanf("%d", &node[i].data);
node[i].leftchild = NULL;
node[i].rightchild = NULL;
}
printf("Generating your huffman tree......\nDone!\n");
return ( Huffman_Generate( node, n ) );
}
void main()
{
struct BTREE *m;
m = Huffman();
print_preorder_recursion( m );
putchar('\n');
} |
-
已经创建的霍夫曼树
-
执行完这个if语句左子树的值居然变了???
|