OS:XP-pro
開発環境:VC++.NET2002
トラバーサル(全て探索)の所が全く分かりません。
以下の//********の所です
何度もシミュレーションしてみたのですが・・・
#include<stdio.h>//2分探索木--トラバーサルの非再帰版
#include<string.h>
#include<stdlib.h>
#define MaxSize 256
struct tnode{
struct tnode *left;
char name[20];
struct tnode *right;
}*temp1,*temp2,*head,*w[128];
struct tnode *gentree(struct tnode *a,struct tnode *temp2);
void search(char *key,struct tnode *a);
void disp(struct tnode *a);
void _free(struct tnode *a);
int main(void){
temp1=(struct tnode *)malloc(sizeof(struct tnode));
temp1->right=temp1->left=NULL;temp1->name[0]='\0';
head=temp1;
disp(head);
while(1){
temp2=(struct tnode *)malloc(sizeof(struct tnode));
temp2->left=temp2->right=NULL;
printf("追加したい名前>>");
if(fscanf(stdin,"%s",temp2->name)==EOF)break;
rewind(stdin);
gentree(head,temp2);
disp(head);
}
while(1){
printf("探したい人の名前を入力して下さい>>");
if(fscanf(stdin,"%s",temp2->name)==EOF)break;
rewind(stdin);
search(temp2->name,head);
disp(head);
}
free(temp2);
_free(head);
return(0);
}
struct tnode *gentree(struct tnode *head,struct tnode *temp2){
struct tnode *i=head;
if(i==NULL)return(temp2);
if(strcmp(i->name,temp2->name)>0)i->left=gentree(i->left,temp2);
else if(strcmp(i->name,temp2->name)<0)i->right=gentree(i->right,temp2);
else printf("名前:%sは既にいますので追加できません\n",temp2->name);
return(i);
}
void search(char *key,struct tnode *head){
struct tnode *i=head;
if(i==NULL){
printf("名前:%sはいません\n",key);
return;
}
if(strcmp(i->name,key)>0)search(key,i->left);
else if(strcmp(i->name,key)<0)search(key,i->right);
else{
printf("名前:%sは見つかりました\n",i->name);
printf("%10p%10s%10p\n",i->left,i->name,i->right);
}
}
void disp(struct tnode *head){
int sp=0;
struct tnode *temp1=head->right;
while(!(sp==0&&temp1==NULL)){ //****************************
while(temp1!=NULL){ //****************************
w[sp++]=temp1; //****************************
temp1=temp1->left; //****************************
} //****************************
sp--; //****************************
printf("%s\n",w[sp]->name); //****************************
temp1=w[sp]->right; //****************************
} //****************************
}
void _free(struct tnode *a){
struct tnode *temp1=a;
if(temp1==NULL)return;
disp(temp1->left);
disp(temp1->right);
free(temp1);
}