题目要求:
二叉树算法设计
TXT文件内容(Btree.txt):
1 2 4 8 0 0 9 0 0 5 0 0 3 6 0 0 7 0 0
一定注意,这里文件按照前序遍历的数字形式,空树按照0进行表示,每个数字间空格,这样能区分十位数还是个位数,并且只能是纯数字
代码展示:
#include<iostream>
#include<stdio.h>
#include<malloc.h>
#include<queue>
#include <string.h>
using namespace std;
typedef int ElemType;
#define MaxSize 100
char array[MaxSize];//用于存储文件当中的信息
int str[MaxSize];
int flag=0;
int str1[MaxSize];
int cunchu[MaxSize];
int kkk=0;//数字数组分完单词后长度
typedef struct BiTNode{
ElemType data;
struct BiTNode *lchild,*rchild;
int ltag,rtag;
}BiTNode,*BiTree;
BiTree CreateBiTree()//这里输入的空树是以0表示
{
int e=str[flag++];//血的教训,递归的传值问题
// cout<<flag;
BiTree T;
if(e==0)T=NULL;
else
{
T=(BiTNode*)malloc(sizeof(BiTNode));
if(!T)return 0;
T->data=e;
T->lchild=CreateBiTree();
T->rchild=CreateBiTree();
}
return T;
}
void openfile1(){
//打开文件存储树的信息
FILE *fp;
int i=0,len=0,temp1=0;
char temp;
if((fp=fopen("1.Btree.txt","r"))==NULL){
cout<<"文件打开失败"<<endl;
exit(0);
}
while(!feof(fp)){
// if(fgetc(fp)=='/0')break;
temp=fgetc(fp);
array[i]=temp;//将字符一一存入所定义的字符串
//cout<<array[i]<<" ";;
i++;len++;
}
printf("\n");
//cout<<len-1<<"hhhh"<<endl;
for(int i=0;i<len-1;i++){
//注意要少一位,最后的那个符号不需要
str1[i]=(int)(array[i]-'0');
//cout<<str1[i]<<" ";
}
str1[i+1]=(int)(' '-'0');
//cout<<str1[i+1]<<endl;
int iii=0,jjj=0,cunchutemp=0;
while(iii<len){
//cout<<"OK"<<endl;
if(str1[iii]==-16){
cunchutemp=0;
for(int i=0;i<=jjj-1;i++){
cunchutemp=cunchu[i]+cunchutemp*10;
//cout<<"计算的数值为"<<cunchutemp<<endl;
}
str[kkk]=cunchutemp;
//cout<<str[kkk]<<endl;
//cout<<"kkk的值为"<<kkk<<endl;
kkk++;
memset(cunchu,0,sizeof(cunchu));
iii++;
jjj=0;
}
else{
//cout<<"进入过一次"<<endl;
cunchu[jjj]=str1[iii];
jjj++;iii++;
}
}
printf("\n");
//cout<<str1[0]<<str1[1]<<endl;
for(int i=0;i<kkk+1;i++){
cout<<str[i]<<" ";
}
return ;
}
int openfile(){
//打开文件存储树的信息
FILE *fp;
int i=0,len=0,temp1=0;
char temp;
if((fp=fopen("Btree.txt","r"))==NULL){
cout<<"文件打开失败"<<endl;
exit(0);
}
while(!feof(fp)){
// if(fgetc(fp)=='/0')break;
temp=fgetc(fp);
array[i]=temp;//将字符一一存入所定义的字符串
// cout<<array[i];
i++;len++;
}
for(int i=0;i<len-1;i++){
//注意要少一位,最后的那个符号不需要
str[i]=