본문 바로가기

알고리즘 & 자료구조

2진 트리

2진 트리를 만들어 봤습니다.

한동안 알고리즘과 자료구조를 공부를 안했는데

확실히 만들면서 머리가 아파오기 시작했습니다.

테스트 해보니 다행히 이상없이 잘 돌아가기는 했고..

역시 많이 부족해...
(소스는 어렵지 않으니 분석해 보시길..)





#include <stdio.h>
#include <stdlib.h>


typedef struct _node
{
    struct _node *left;
    struct _node *right;
    int num;
}node;


node *head=NULL;


void InsertNode(int num);   // 자료 입력
void SearchTree(node *comp, node *tmp);  // 입력값이 어디에 들어가야 하나?
void PrintTree(node *comp); // 자료 출력
void FreeTree(node *comp); // 동적메모리 할당 해제


int main()
{
    int num;
    int i;


    for(i=0;i<5;i++) {
        scanf("%d", &num);
        InsertNode(num);
    }

    PrintTree(head);

    FreeTree(head);

    return 0;
}



void InsertNode(int num)
{
    node *tmp;
    node *comp=head;

    tmp=(node *)malloc(sizeof(node));
    tmp->left=NULL;
    tmp->right=NULL;
    tmp->num=num;

    if(comp!=NULL)
        SearchTree(comp, tmp);
    else
        head=tmp;
}


void SearchTree(node *comp, node *tmp)
{
    if(comp->num > tmp->num) {
        if(comp->left != NULL)
            SearchTree(comp->left, tmp);
        else
            comp->left=tmp;
    }
    else if(comp->num < tmp->num) {
        if(comp->right != NULL)
            SearchTree(comp->right, tmp);
        else
            comp->right=tmp;
    }
}


void PrintTree(node *comp)
{
    if(comp->left!=NULL)
        PrintTree(comp->left);
    if(comp->right!=NULL)
        PrintTree(comp->right);

    printf("num : %d\n", comp->num);
}

void FreeTree(node *comp)
{
    if(comp->left!=NULL)
        FreeTree(comp->left);
    if(comp->right!=NULL)
        FreeTree(comp->right);

    free(comp);
}