C/C++ 언어 이진 트리를 생성하고 전위, 중위, 후위 순회 연산 결과를 구하는 예제


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <stdio.h>
#include <stdlib.h>
 
struct treeNode {
  struct treeNode *leftPtr;
  int data;
  struct treeNode *rightPtr;
 };
 
typedef struct treeNode TREENODE;
typedef TREENODE *TREENODEPTR;
 
void insertNode(TREENODEPTR *int);
void inOrder(TREENODEPTR);
void preOrder(TREENODEPTR);
void postOrder(TREENODEPTR);
 
void main(void) {
  int i = 0;
  int item = 0;
  TREENODEPTR rootPtr = NULL;
 
  printf("이진 트리를 구성하기 위한 데이터(숫자)를 입력하여 주세요\n");
 
  for (i = 0; i < 10; i++) {
    printf("insert : ");
    scanf("%d", &item);
    insertNode(&rootPtr, item);
  }
 
  printf("\n\nThe preOrder traversal is: \n");
  preOrder(rootPtr);
 
  printf("\n\n The inOrder traversal is:\n");
  inOrder(rootPtr);
 
  printf("\n\nThe postOrder traversal is: \n");
  postOrder(rootPtr);
  printf("\n");
}
 
void preOrder(TREENODEPTR treePtr) {
  if (treePtr != NULL) {
    printf("%3d", treePtr->data);
    preOrder(treePtr -> leftPtr);
    preOrder(treePtr -> rightPtr);
  }
}
 
void insertNode(TREENODEPTR *treePtr, int value)  {
  if (*treePtr == NULL) { /* *treePtr is NULL */
    *treePtr = (TREENODE*)malloc(sizeof(TREENODE));
    if (*treePtr != NULL) {
      (*treePtr) -> data = value;
      (*treePtr) -> leftPtr = NULL;
      (*treePtr) -> rightPtr = NULL;
    }
    else
      printf("\n%d not inserted. No memory available.\n", value);
  }
  else if (value < (*treePtr)->data)
    insertNode(&((*treePtr)->leftPtr),value);
  else if (value > (*treePtr) -> data)
    insertNode(&((*treePtr)->rightPtr)  ,value);
  else
    printf("dup\n"); /* dup(duplicate)는 같은 원소가 두번 나타날 때 사용 */
}
 
void inOrder(TREENODEPTR treePtr) {
  if (treePtr != NULL) {
    inOrder(treePtr->leftPtr);
    printf("%3d", treePtr->data);
    inOrder(treePtr->rightPtr);
  }
}
 
void postOrder(TREENODEPTR treePtr) {
  if (treePtr != NULL) {
    postOrder(treePtr -> leftPtr);
    postOrder(treePtr -> rightPtr);
    printf("%3d", treePtr->data);
  }
}
cs


C/C++ 언어 이진 트리를 생성하고 전위, 중위, 후위 순회 연산 결과를 구하는 예제




+ Recent posts