会员
众包
新闻
博问
闪存
赞助商
HarmonyOS
Chat2DB
所有博客
当前博客
我的博客
我的园子
账号设置
会员中心
简洁模式
...
退出登录
注册
登录
1989huangkq
huangkq1989
博客园
|
首页
|
新随笔
|
新文章
|
联系
|
订阅
|
管理
将二叉树写入文件,再读出重新构建
代码如下:
/******************************* * * 功能:生成一棵二叉树,写进文件,再读出, * 并将其重构成一个二叉树 * * author:kangquan2008@scut blog:<a href="http://blog.csdn.net/kangquan2008">http://blog.csdn.net/kangquan2008</a> * ******************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_SIZE 20 typedef struct Node{ char data; struct Node * lchild; struct Node * rchild; }* Tree,Node; void create_tree(Tree * tree) { int data,data2; data = fgetc(stdin); data2 = getc(stdin);// 吸收回车键,或用 getchar() :) 注意返回值是整数! if(data == 'z')// 遇到z结束 { *tree = NULL; return ; } if(!(*tree = malloc(sizeof(Node)))) exit(-1); (*tree)->data = data; create_tree(&((*tree)->lchild)); create_tree(&((*tree)->rchild)); } void pre_order_fun(Tree tree) { if(tree == NULL) return ; printf("%c ",tree->data); pre_order_fun(tree->lchild); pre_order_fun(tree->rchild); } void in_order_fun(Tree tree) { if(tree == NULL) return ; in_order_fun(tree->lchild); printf("%c ",tree->data); in_order_fun(tree->rchild); } void pre_order_file(Tree tree,FILE * file) { if(tree == NULL) return ; printf("%c ",tree->data); fputc(tree->data,file); pre_order_file(tree->lchild,file); pre_order_file(tree->rchild,file); } void in_order_file(Tree tree,FILE * file) { if(tree == NULL) return ; in_order_file(tree->lchild,file); printf("%c ",tree->data); fputc(tree->data,file); in_order_file(tree->rchild,file); } void get_from_file(char pre[],char in[],FILE * file) { char all[MAX_SIZE * 2]; rewind(file); fgets(all,sizeof(all),file); int i; for(i=0; i<strlen(all); i++) { if(i < strlen(all)/2) pre[i] = all[i]; else in[i-strlen(all)/2] = all[i]; if(i == strlen(all)/2) pre[i] = '\0'; } in[i-strlen(all)/2] = '\0'; } void form_tree(char pre[],char in[],int len,Tree * tree) { if(len > 0) { char * p = in; for(; p!= NULL; p++) if(*p == *pre) break; int left_size = p - in; *tree = malloc(sizeof(Node)); (*tree)->data = *pre; (*tree)->lchild = NULL; (*tree)->rchild = NULL; form_tree(pre+1,in,left_size,&((*tree)->lchild)); form_tree(pre+left_size+1,p+1,len-left_size-1,&((*tree)->rchild)); } } int main() { Tree tree = NULL; create_tree(&tree); FILE * file; file = fopen("./test.txt","w+"); if(file == NULL) { printf("can not open!"); exit(EXIT_FAILURE); } pre_order_file(tree,file); in_order_file(tree,file); puts(""); char pre[MAX_SIZE] ;//= "1234567"; char in[MAX_SIZE] ;//= "3241657"; get_from_file(pre,in,file); puts(pre); puts(in); Tree target_tree = NULL; form_tree(pre,in,strlen(pre),&target_tree); pre_order_fun(target_tree); in_order_fun(target_tree); return 0; } /* 1 2 3 z z 4 z z 5 6 z z 7 z z 按上面的输入,即可生成下面的树,写入文件并读出重新构建 1 2 5 3 4 6 7 */
发表于
2011-10-04 19:29
huangkq1989
阅读(
764
) 评论(
0
)
收藏
举报
刷新页面
返回顶部
公告