-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Search_1.cpp
More file actions
118 lines (104 loc) · 2.18 KB
/
Binary_Search_1.cpp
File metadata and controls
118 lines (104 loc) · 2.18 KB
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
#include <bits/stdc++.h>
#include <string>
using namespace std;
typedef long long llong;
// 二分木の定義
struct Node {
int key;
Node *left, *right, *parent;
};
// 根・葉を定義
Node *root, *NIL;
// 二分木に新しい値を挿入する
void insert(int key)
{
Node *x, *y, *z;
// 初期化
z = new Node;
z->key = key;
z->left = NIL;
z->right = NIL;
y = NIL;
x = root;
// 根から適切な位置までたどる
while (x != NIL) {
y = x; // 親を設定
if (z->key < x->key) {
x = x->left;
}
else {
x = x->right;
}
}
z->parent = y;
// 要素を配置する場所を決定する
if (y == NIL) { // T が空の場合
root = z;
}
else if (z->key < y->key){
y->left = z; // z を y の左の子にする
}
else {
y->right = z; // z を y の右の子にする
}
}
// 根から先行順巡回を行う
// 親→左部分木→右部分木の順
void PreOrder(Node* node)
{
cout << " " << node->key;
// 左部分木をチェック
if (node->left != NIL) {
PreOrder(node->left);
}
// 右部分木をチェック
if (node->right != NIL) {
PreOrder(node->right);
}
}
// 根から先行順巡回を行う
// 左部分木→親→右部分木の順
void InOrder(Node* node)
{
// 左部分木をチェック
if (node->left != NIL) {
InOrder(node->left);
}
cout << " " << node->key;
// 右部分木をチェック
if (node->right != NIL)
{
InOrder(node->right);
}
}
void PrintVec()
{
// 先行順巡回、 中間順巡回
InOrder(root);
cout << "\n";
PreOrder(root);
cout << "\n";
}
int main() {
// 節点の個数
int n = 0;
// 次数
int iDeg = 0;
int iNodeIdx = 0;
int left, node;
string strCmd;
cin >> n;
for (int i = 0; i < n; i++)
{
//節点番号を取得
cin >> strCmd;
if (strCmd == "insert") {
cin >> iNodeIdx;
insert(iNodeIdx);
}
else if (strCmd == "print") {
PrintVec();
}
}
return 0;
}