Created
May 30, 2019 06:45
-
-
Save blood72/bea578d4cf73231fbc7116d50ee1994e to your computer and use it in GitHub Desktop.
학창 시절에 만든 C언어 이진 트리 순회
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct TreeNode | |
{ | |
int data; | |
struct TreeNode *llink, *rlink; | |
} TreeNode; | |
/* | |
순회 | |
*/ | |
// 중위 순회 | |
void inorder(TreeNode *root) | |
{ | |
if(root) | |
{ | |
inorder(root->llink); // 왼쪽 서브 트리 순회 | |
printf("%d ",root->data); | |
inorder(root->rlink); // 오른쪽 서브 트리 순회 | |
} | |
} | |
// 전위 순회 | |
void preorder(TreeNode *root) | |
{ | |
if(root) | |
{ | |
printf("%d ",root->data); | |
preorder(root->llink); // 왼쪽 서브 트리 순회 | |
preorder(root->rlink); // 오른쪽 서브 트리 순회 | |
} | |
} | |
// 후위 순회 | |
void postorder(TreeNode *root) | |
{ | |
if(root) | |
{ | |
preorder(root->llink); // 왼쪽 서브 트리 순회 | |
preorder(root->rlink); // 오른쪽 서브 트리 순회 | |
printf("%d ",root->data); | |
} | |
} | |
//노드 생성 | |
void CreateTree(TreeNode **root, int value) | |
{ | |
TreeNode *new_tree; // 새 트리 생성 | |
TreeNode *temprt = *root; // 임시트리 | |
TreeNode *prevrt = *root; // temprt의 이전트리 | |
new_tree = (TreeNode *)malloc(sizeof(TreeNode)); | |
new_tree->data = value; | |
new_tree->llink = NULL; | |
new_tree->rlink = NULL; | |
if(*root == NULL) | |
*root = new_tree; | |
else | |
{ | |
while(temprt != NULL) | |
{ | |
if(new_tree->data == temprt->data) | |
{ | |
printf("트리 내 키 값이 존재합니다.\n"); | |
break; | |
} | |
prevrt = temprt; | |
if(new_tree->data < temprt->data) | |
temprt = prevrt->llink; | |
else | |
temprt = prevrt->rlink; | |
} | |
if(prevrt != NULL) | |
if (new_tree->data < prevrt->data) | |
prevrt->llink = new_tree; | |
else | |
prevrt->rlink = new_tree; | |
else | |
printf("얘기치 못한 에러입니다.\n"); | |
} | |
} | |
int main() | |
{ | |
TreeNode *root = NULL; | |
int value; | |
char command = {'\0'}; | |
do | |
{ | |
printf("데이터를 입력하세요 : "); | |
scanf("%d",&value); | |
CreateTree(&root, value);//새 트리 생성 | |
fflush(stdin); | |
printf("트리순회 //1-중위, 2-전위, 3-후위\n"); | |
printf("트리를 계속 만드시겠습니까? (y/n) : "); | |
scanf("%c",&command); | |
switch(command) | |
{ | |
case '1': | |
inorder(root); // 중위 | |
break; | |
case '2': | |
preorder(root); // 전위 | |
break; | |
case '3': | |
postorder(root);// 후위 | |
break; | |
} | |
} while(command == 'y'); | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment