본문 바로가기

Computer Science

Binary Tree

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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <iostream>
using namespace std;
int n = 15;
typedef struct Node
{
    char data;
    struct Node *left;
    struct Node *right;
};
////////////////이진탐색 트리 //////////////
void insertNode(Node *node, char data)
{
    Node *parent;
    Node *tmp;
    Node *newNode;
    parent = NULL;
    tmp = node;
    while (tmp != NULL)
    {
        parent = tmp;
        if (tmp->data > data)
        {
            if (tmp->left != NULL)
            {
                //왼쪽 자식을 타고 내려간다.
                tmp = tmp->left;
            }
            else
                break;
        }
        else
        {
            //오른쪽 자식
            if (tmp->right != NULL)
            {
                tmp = tmp->right;
            }
            else
                break;
        }
        newNode = new Node;
        if (parent->data > data)
        {
            parent->left = newNode;
        }
        else
        {
            parent->right = newNode;
        }
        newNode->left = NULL;
        newNode->right = NULL;
        newNode->data = data;
    }
}
////////////////이진탐색 트리 //////////////
void postOrder(Node *root)
{
    if (root)
    {
        postOrder(root->left);
        postOrder(root->right);
        cout << root->data << '\n';
    }
}
void preOrder(Node *root)
{
    if (root)
    {
        cout << root->data << '\n';
        preOrder(root->left);
        preOrder(root->right);
    }
}
void inOrder(Node *root)
{
    if (root)
    {
        cout << root->data << '\n';
        preOrder(root->left);
        preOrder(root->right);
    }
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    ///이진 트리 ////
    // int n;
    // cin >> n;
    Node nodes[n + 1];
    //init
    for (int i = 1; i <= n; i++)
    {
        nodes[i].data = i;
        nodes[i].left = NULL;
        nodes[i].right = NULL;
    }
    for (int i = 2; i <= n; i++)
    {
        if (i % 2 == 0)
        {
            //왼쪽 자식
            nodes[i / 2].left = &nodes[i];
        }
        else
        {
            nodes[i / 2].right = &nodes[i];
        }
    }
    preOrder(&nodes[1]);
    inOrder(&nodes[1]);
    postOrder(&nodes[1]);
    return 0;
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

'Computer Science' 카테고리의 다른 글

올림, 내림, 반올림 함수  (0) 2019.08.29
c++ 문자열 변환  (0) 2019.08.28
Binary Search Tree  (0) 2019.08.09
HashMap 정렬  (0) 2019.05.03
Java에서 HexString 값을 int로 변경  (0) 2019.05.03