이진트리탐색 결과를 txt파일로 저장하고싶은데 도와주세요ㅠㅠ
일진오빠
질문 제목 : 외부 파일에서 받아온 숫자들을 BST로 구성하여 그 걸과를 다시 다른txt파일로 저장하려고 하는데 어떻게 해야할까요?ㅠㅠ질문 요약 :1. 파일입력을 하나하나 받을때마다 노드에 넣어서 정렬을 하는 식으로 코드를 짯는데 이렇게 햇더니 fprintf에서 막혀버렸어요 ㅠㅠ
2. 애초에 외부데이터를 받아올때 배열로 받아왔었어야 할까요?ㅠㅠㅠ
질문 내용 :
#include stdio.h
#include stdlib.h
typedef struct treeNode{
int key;
struct treeNode *left;
struct treeNode *right;
}treeNode;
typedef int element;
treeNode* insertNode(treeNode *p, int x) //트리에 데이터 삽입하는 함수
{
treeNode *newNode;
if(p==NULL){
newNode = (treeNode*)malloc(sizeof(treeNode));
newNode-key = x;
newNode-left = NULL;
newNode-right=NULL;
return newNode;
}
else if (x p-key)
p-left = insertNode(p-left , x);
else if (x p-key)
p-right = insertNode(p-right , x);
else
printf(\n 이미 같은키 있음 \n);
return p;
}
treeNode* searchBST(treeNode *root, int x) //트리에 숫자가 있는지 검색하는 함수
{
treeNode *p;
p = root;
while(p != NULL){
if(x p-key )
p= p-left;
else if(x == p-key)
return p;
else
p=p-right ;
}
printf(\n 찾는키 ㄴㄴ);
return p;
}
void displayInorder(treeNode *root)
{
if(root){
displayInorder(root-left);
printf(%d , root-key);
displayInorder(root-right);
}
}
void menu()
{
printf(\n*-------------------------------*);
printf(\n\t1 : 트리 출력 및 외부저장 );
printf(\n\t2 : 숫자 검색 );
printf(\n\t3 : 종료 );
printf(\n*------------------------------*);
printf(\n 메뉴 입력 );
}int main() ///////메인함수 시작
{ int key;
int choice;treeNode* root=NULL;
treeNode* foundedNode = NULL;
int Temp[50];
int in;
int t;FILE*fp;
FILE*fp1;
fp=fopen(DATA.txt,r);
fp1=fopen(out.txt,w);
while(1){
menu();
scanf(\n %d,&choice);
switch(choice){
case 1 : printf(\t[이진트리 출력] );
if(root==NULL)//root가 NULL이라면
{
fscanf(fp,%d,&in);//파일 fscanf 받음
root=insertNode(root,in);//받은값을 강제로 루트값으로 고정
}
while( fscanf(fp,%d,&in) !=EOF)//파일이 끝날때까지 입력을 받으며
{
insertNode(root,in);//insertNode에 인자로 넣어준다
}displayInorder(root);
printf(\n);
break;
case 2 : printf(찾을 문자를 입력하세요 : );
scanf(\n%d,&key);
foundedNode=searchBST(root, key);
if(foundedNode != NULL)
printf(\n %d 를 찾음 \n, foundedNode-key );
else
printf(\n 문자 ㄴㄴ \n);
break;
case 3:
return 0;default : printf(없는 메뉴다해 다시 선택 \n);
break;
}
}fclose(fp);
fclose(fp1);
}넣은 데이터(DATA.txt)30
40
27
13
67
35
38
87
96
234
25
2
82아예 삽입,정렬 하는 코드 (case 1)을 뜯어고치는게 나을까요??ㅠㅠㅠㅠ