2016년 8월 29일 월요일

C++ - 2진 트리

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
84
85
86
87
88
89
90
91
92
93
94
95
#include <iostream>
#include <stdlib.h>
 
using namespace std;
 
typedef struct Tree {
    int data;
    struct Tree *left;
    struct Tree *right;
}treeNode;
 
treeNode *InsertNode(treeNode *L, int pData) {
    treeNode *root;
    if (L == NULL) {
        root = new treeNode;
        root->left = NULL;
        root->right = NULL;
        root->data = pData;
        return root;
    }
    else if(pData < L->data) {
        L->left = InsertNode(L->left, pData);
    }
    else if (pData > L->data) {
        L->right = InsertNode(L->right, pData);
    }
    else {
        cout << "[ 중복이야 다른거 ]" << endl;
    }
    return L;
}
 
treeNode *SearchNode(treeNode* root, int pData) {
    treeNode* p = root;
    while (p != NULL){
        if (pData < p->data) {
            p = p->left;
        }
        else if (pData == p->data) {
            cout << "[ 존재하는 숫자입니다. ]" << endl;
            return p;
        }
        else {
            p = p->right;
        }
    }
    cout << "[ 찾는 문자가 없습니다. ]" << endl;
}
 
void PreOrder(treeNode *root) {
    if (root) {
        cout << root->data << " ";
        PreOrder(root->left);
        PreOrder(root->right);
    }
}
 
int main() {
 
    int searchNum = NULL;
    int insertNum = NULL;
    int num = 0;
    treeNode* root = InsertNode(NULL5);
 
    while (1) {
        cout << "무엇을 할지 번호를 입력해주세요" << endl << "1. 삽입" << endl << "2. 검색" << endl << "3. 출력" << endl << "4. 끝내기" << endl << "번호 입력 : ";
        cin >> num;
        switch (num)
        {
        case 1:
            cout << "삽입할 번호를 써주세요 : ";
            cin >> insertNum;
            InsertNode(root, insertNum);
            PreOrder(root);
            break;
        case 2:
            cout << "검색할 번호를 써주세요 : ";
            cin >> searchNum;
            SearchNode(root, searchNum);
            break;
        case 3:
            cout << "[ 출력 ]" << endl;
            PreOrder(root);
            break;
        case 4:
            cout << "[ 끝내기. ]" << endl;
            return 0;
        default:
            cout << "[ 메뉴에 없는 번호입니다. 다시 입력해주세요. ]" << endl;
            break;
        }
 
    }
    return 0;
}
cs

댓글 없음:

댓글 쓰기