-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Search_2.cpp
More file actions
148 lines (132 loc) · 3.04 KB
/
Binary_Search_2.cpp
File metadata and controls
148 lines (132 loc) · 3.04 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
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
#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 の右の子にする
}
}
// キーが存在するか確認する
bool find(Node* node, int key)
{
while (node != NIL) {
if (node->key == key) return true;
// 二分木の特性を利用して場合分け
// 探すキーと現在のキーの子の左右の大小を比較する
// 終了
if (node->key == key) {
return true;
} else if (node->key < key)
{
// 右の子ノードよりキーが大きければ右へ
node = node->right;
} else {
// 左の子ノードよりキーが小さければ左へ
node = node->left;
}
}
return false;
}
// 根から先行順巡回を行う
// 親→左部分木→右部分木の順
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,strRes;
bool bRet = false;
cin >> n;
for (int i = 0; i < n; i++)
{
//節点番号を取得
cin >> strCmd;
if (strCmd == "insert") {
cin >> iNodeIdx;
insert(iNodeIdx);
}
else if (strCmd == "print") {
PrintVec();
}
else if(strCmd == "find") {
cin >> iNodeIdx;
bRet = find(root, iNodeIdx);
strRes = bRet? "yes" : "no";
cout << strRes << "\n";
}
}
return 0;
}