Binary Tree, Binary Search Tree, Binary Heap 메모

1. BinaryTree = 말 그대로 이진트리. 

이 자료구조는 노드당 0~2개의 자식을 지닌다.채워지는 순서는 뿌리부터 채워져있는지 확인하고, 그다음 왼쪽 자식에서 오른쪽 자식으로 채워지며 모두 채워졌으면 그 자식의 자식으로 순환한다.

1-1 Full Binary Tree or Strict Binary Tree

자식이 2개 혹은 0인 트리다.



1-2 Complete Binary Tree

마지막레벨을 제외한 모든 레벨이 채워져있고 노드가 왼쪽에서 오른쪽으로 순서대로 채워져있는 트리.

      0                                          0

   0     0                                    0    0

0  0   X  0                               0  0  0

    NO                                       OK

1-3 Perfect Binary Tree

모든 노드는 2개의 자식을 지니며 동일한 레벨을 갖는다.

       0

    0    0

  0  0  0  0

     OK

1-4 Balanced Binary Tree

왼쪽과 오른쪽 높이 차이가 1 레벨식 나뉘어져있는 것

       0                                  0

     0   0                            0     

  0  0                              0  0

    OK                                NO


2. Binary Search 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <array>
#include <cmath>
using namespace std;
 
struct TreeNode
{
    int data;
    TreeNode* left;
    TreeNode* right;
 
    TreeNode(int _data)
    {
        left = NULL;
        right = NULL;
        data = _data;
    }
};
 
class BinarySearchTree
{
    TreeNode* root;
 
public:
    BinarySearchTree()
    {
        root = NULL;
    }
 
    bool isEmpty()
    {
        return root == NULL;
    }
 
    void insert(int data)
    {
        TreeNode* newNode = new TreeNode(data);
        if (isEmpty())
        {
            root = newNode;
            return;
        }
        TreeNode* temp = root;
 
        TreeNode* prev = nullptr;
        while (temp != NULL// 데이터 크기에 알맞는 곳을 찾고 prev를 그 전적을 기억하게 둔다.
        {
            prev = temp;
 
            if (data > temp->data) temp = temp->right;
            else if (data < temp->data) temp = temp->left;
            else cout << "This object already exists in the tree \n";
 
        }
 
        if (data >= prev->data)
        {
            prev->right = newNode;
        }
        else if (data < prev->data) prev->left = newNode;
    }
 
 
 
    void deleteNode(TreeNode* root,int key)
    {
        TreeNode* parent = nullptr;
        TreeNode* cur = root;
 
 
        searchKey(cur, key, parent); // search the key in BST and set to parent.
 
        if (cur == nullptr)return;
 
        // Case 1: if deleteNode has no children
        if (cur->left == nullptr && cur->right == nullptr)
        {
            if (cur != root)
            {
                if (parent->left == cur)parent->left = nullptr;
                else parent->right = nullptr;
            }
            else root = nullptr;
            free(cur);
 
        } 
        // Case 2: has two children
        else if(cur->left && cur->right)
        {
            TreeNode* successor = GetMinimumKey(cur->right);
            int value = successor->data;
 
            deleteNode(root, successor->data);
            cur->data = value;
            ///
            /// 1.
            ///        12
            ///      5    15   <- deleteNode
            ///    3    13  17 <- minimumKey in cur-Right
            ///           14   19
            /// 
            /// 2.
            ///        12
            ///      5    17   <- cur->data = value;
            ///    3    13  17 <- deleteNode(successor)
            ///           14   19
            /// 
            /// 3.            
            ///        12
            ///      5    17   
            ///    3    13  19
            ///           14   
        }
        // Case 3: has one children
        else
        {
            TreeNode* child;
 
            if (cur->left == nullptr) child = cur->right;
            else child = cur->left;
 
            if (cur != root)
            {
                if (cur == parent->left) parent->left = child;
                else parent->right = child;
            }
            else
            {
                root = child;
            }
            free(cur);
        }
    }
 
    void searchKey(TreeNode*& cur, int key, TreeNode*& parent)
    {
        while (cur != nullptr && cur->data != key)
        {
            parent = cur;
 
            if (key < cur->data) cur = cur->left;
            else cur = cur->right;
        }
    }
 
    TreeNode* GetMinimumKey(TreeNode* cur)
    {
        while (cur->left != nullptr)
        {
            cur = cur->left;
        }
        return cur;
    }
 
 
 
    TreeNode* getRoot()
    {
        return root;
    }
 
    void inorder(TreeNode* node) // 중위순회
    {
        if (node != NULL)
        {
            inorder(node->left);
            cout << node->data << " ";
            inorder(node->right);
        }
 
        ///       1
        ///     2   3
        ///   4  5 6  7
        /// 
        ///  4 2 5 1 6 3 7
    }
 
    void postorder(TreeNode* node) // 후위순회
    {
        if (node != NULL)
        {
            postorder(node->left);
            postorder(node->right);
            cout << node->data << " ";
        }
        ///       1
        ///     2   3
        ///   4  5 6  7
        /// 
        /// 4 5 2 6 7 3 1
 
    }
 
    void preorder(TreeNode* node) // 전위순회
    {
        if (node != NULL)
        {
            cout << node->data << " ";
            preorder(node->left);
            preorder(node->right);
        }
        ///       1
        ///     2   3
        ///   4  5 6  7
        ///
        ///  1 2 4 5 3 6 7
 
    }
 
    void Print(TreeNode* node,int space = 0)
    {
        if (node == NULL)
        {
            return;
        }
        space += 10;
 
        Print(node->right, space);
 
        cout << endl;
 
        for (int i = 10; i < space; i++)
        {
            cout << " ";
        }
        cout << node->data << "\n";
 
        Print(node->left, space);
    }
};
 
void add(int a, int b, int& sum)
{
    sum = a + b;
}
 
void add(int a, int b, int* sum)
{
    *sum = a + b;
}
 
int main()
{
    BinarySearchTree tree;
 
    tree.insert(5);
    tree.insert(8);
    tree.insert(2);
    tree.insert(7);
    tree.insert(4);
    tree.insert(1);
    tree.insert(10);
 
    tree.deleteNode(tree.getRoot(), 7);
    tree.Print(tree.getRoot());
 
}
 
 
cs

2 - 1 AVL Tree = Adelson - Velsky - Landis 발명자 이름을 따 만든 tree

BalanceFactor = height(left) - height(right).

높이차이가 1을 초과하면 회전(Rotation)을 통해 균형을 잡는다.


3. Heap orBinary Heap = 이진 힙이다.

기본 형태는 이진트리다. 차이점이라면야 이진탐색트리는 크기순이 왼쪽 자식 < 부모 < 오른쪽 자신인 반면 힙은 왼쪽 < 오른쪽 < 부모식으로 크다. 또한 삽입조건이 존재하지 않는 대신 Heapify 를 하여 정렬한다.


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
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <array>
 
using namespace std;
 
class BinaryHeap
{
private:
    int* heap;
    int curCount;
    int leftchildIndex(int i) {return i * 2 + 1; }
    int rightchildIndex(int i) {return i * 2 + 2; }
    int parentIndex(int i) {return (i - 1/ 2; }
    void Swap(int& a,int &b)
    {
        int temp = a;
        a = b;
        b = temp;
    }
    void heapifyup(int i)
    {
        int parent = parentIndex(i);
 
        if (heap[parent] > heap[i]) 
        {
            Swap(heap[i], heap[parent]);
            heapifyup(parent);
        }
        
    }
    void heapifydown(int i)
    {
        int left = leftchildIndex(i);
        int right = rightchildIndex(i);
        int smallest = i;
 
        // 자식노드의 인덱스(주소)값이 배열 길이 미만이며
        // 자식노드중에 하나라도 자신(부모)보다 비교 값이 적다면,
        // 또 둘다 값이 적다면 서로 비교해 가장 적은 인덱스를 고른다.
        if (left < curCount && heap[left] < heap[i])
        {
            smallest = left;
        }
        if (right < curCount && heap[right] < heap[smallest])
        {
            smallest = right;
        }
 
        //  윗 조건부에 하나라도 부합이 되면 계속 재귀한다.
        if (smallest != i) 
        {
            Swap(heap[i], heap[smallest]);
            heapifydown(smallest);
        }
 
    }
 
public:
 
    BinaryHeap(int _maxHeapSize)
    {
        heap = new int[_maxHeapSize];
        curCount = 0;
    }
    int Length() { return curCount; }
 
    void Enqueue(int data)
    {
        heap[curCount] = data;
        heapifyup(curCount);
        curCount++;
    }
 
    int Dequeue()
    {
        int temp = heap[0];
        curCount--;
        heap[0= heap[curCount];
        heapifydown(0); // 뿌리노드 내리기 시작
        return temp;
    }
 
 
    void Print()
    {
        for (int i = 0; i < Length(); i++)
        {
            cout << heap[i] << " ";
        }
 
        cout << endl;
    }
};
cs


3-1 MinHeap 최소힙으로 최솟값을 찾는데 응용한다. 

크기순은 왼쪽 < 오른쪽 < 부모 대로 작다. 


3-2 MaxHeap 최대힙으로 최댓값을 찾는데 응용된다. 

크기순은 왼쪽< 오른쪽 < 부모 대로 크다.










댓글

이 블로그의 인기 게시물

2D 총게임 반동 표시

Simple Stupid Funnel 후기