BST 삽입함수 오류

조회수 782회

typedef struct TreeNode { // BST를 위한 학생 구조체
    char name[100]; // 학생 이름
    int student_number; // 학번
    int score; // 점수는 0~99점
    struct TreeNode *left, *right;
} TreeNode;

void insert_node(TreeNode *root, char name[], int num, int score) //  bst학생 구조체 삽입함수
{
    TreeNode *tmp = root;   // 처음엔 루트
    TreeNode *new = (TreeNode*)malloc(sizeof(TreeNode)); // 새로운 노드 생성
    strcpy(new->name, name);
    new->student_number = num;
    new->score = score;
    new->right = NULL;
    new->left = NULL;

    while (1) {

        if (tmp->score < score) { // tmp의 score값이 새로운 score보다 작다면
            if (tmp->right == NULL) { // 그리고 tmp의 오른쪽이 비었다면
                tmp->right = new; // 오른쪽에 노드 추가
                return;
            }
            else
                tmp = tmp->right; // 오른쪽 있으면 오른쪽 이동
        }
        else {
            if (tmp->left == NULL) { // 위의 상황에서 tmp->score가 score보다 작은 경우
                tmp->left = new;
                return;
            }
            else
                tmp = tmp->left;
        }
    }
}

void init(TreeNode * t)
{
    t->left = NULL;
    t->right = NULL;
}

int main()
{
    Student students[100]; // 학생노드 배열
    int tmp_scores[100]; // 노드 넣을 순서가 저장되어있는 배열
    TreeNode *root; // 루트노드
    root = (TreeNode*)malloc(sizeof(TreeNode));
    init(root); //루트노드 초기화
    FILE * file;
    fopen_s(&file, "Student_info.txt", "rt");   // 읽기용으로 파일 오픈
    if (file == NULL) {                     // 파일 열기 오류판단 문구
        printf("file open error!\n");
        return -1;
    };
    for (int i = 0; i < 100; i++) {            // 파일의 번호, 이름 student 구조체 배열에 넣기
        fscanf(file, "%d %s", &students[i].student_number, &students[i].name);
        students[i].score = i; // 점수는 그냥 0~99 준다
        tmp_scores[i] = i;
        i++;
    }
    fclose(file);   // 파일 닫기

    shuffle(&tmp_scores, 100);   // 배열 섞기
    for (int i = 0; i < 100; i++) {
        insert_node(root, students[tmp_scores[i]].name, students[tmp_scores[i]].student_number, students[tmp_scores[i]].score);
        // 섞은 순서대로 노드 삽입
    }

BST의 삽입함수를 구현한 것입니다. 왜인지는 모르겠지만 이를 실행하면 main함수의 for 구문 안에 있는 insert_node가 실행되지가 않네요.

여러번 확인해본 결과 항상 insert_node를 실행할 때 cmd창이 그대로 멈추고 아무것도 되지 않네요... 함수에 잘못된 부분이 있는 건가요?

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)