#include<bits/stdc++.h>
using namespace std;
typedef struct BiTNode{
char a;
struct BiTNode* left;
struct BiTNode* right;
}BiTNode,*BiTree;
int Search(BiTree &bt,char key,BiTree &p);
void Insert(BiTree &bt,char a);
void Creat(BiTree &bt);
void zhongxu(BiTree &bt);
int Search(BiTree &bt,char key,BiTree &p){
BiTree f=NULL;
BiTree s=bt;
if(s==NULL){
p=f;
return 0;
}
while(s!=NULL){
if(s->a==key){
p=s;
return 1;
}
else if(key<s->a){
f=s;
s=s->left;
}
else{
f=s;
s=s->right;
}
}
p=f;
return 0;
}
void Insert(BiTree &bt,char a){
if(bt==NULL){
bt=(BiTree)malloc(sizeof(BiTNode));
bt->a=a;
bt->left=bt->right=NULL;
}
else{
BiTree b=NULL;
if(Search(bt,a,b)==0){
BiTree c=(BiTree)malloc(sizeof(BiTNode));
c->a=a;
c->left=c->right=NULL;
if(b->a>a){
b->left=c;
}
else{
b->right=c;
}
}
}
}
void Creat(BiTree &bt){
bt=NULL;
FILE* fp;
fp=fopen("二叉排序树.txt","r");
int a;
fscanf(fp,"%d ",&a);
int b;
// cout<<a<<endl;
for(b=0;b<a;b++){
char c;
fscanf(fp,"%c ",&c);
// cout<<c<<endl;
BiTree d=NULL;
if(Search(bt,c,d)==0){
//cout<<"AAa"<<endl;
Insert(bt,c);
}
}
}
void dayin(BiTree &bt){
BiTree a=bt;
//cout<<a<<endl;
while(a!=NULL){
cout<<a->a<<endl;
a=a->right;
}
}
void zhongxu(BiTree &bt){
BiTree a=bt;
if(a!=NULL){
zhongxu(a->left);
cout<<a->a<<endl;
zhongxu(a->right);
}
}
void feidiguizhongxu(BiTree &bt){
FILE* fp=fopen("Tree.txt","w");
BiTree a=bt;
if(bt==NULL){
printf("二叉树为空\n");
return;
}
BiTree b[1000];
int tot=0;
while(a!=NULL||tot>0){
while(a!=NULL){
tot++;
b[tot]=a;
a=a->left;
}
a=b[tot];
tot--;
fprintf(fp,"%c, ",a->a);
a=a->right;
}
}
int main(){
BiTree bt;
Creat(bt);
//dayin(bt);
feidiguizhongxu(bt);
return 0;
}
二叉排序树也
于 2023-12-07 21:57:25 首次发布