-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary search tree.cpp
More file actions
56 lines (48 loc) · 1019 Bytes
/
binary search tree.cpp
File metadata and controls
56 lines (48 loc) · 1019 Bytes
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
//// binary search tree implementation in c++ language ///
#include <bits/stdc++.h>
using namespace std;
struct link {
int val;
link *left;
link *right;
};
#define new_() (link*)malloc(sizeof(link));
link *parent = NULL;
link *temp_parent = NULL;
void Insert (int v) {
link *temp = new_();
temp->val = v;
temp->left = NULL;
temp->right = NULL;
if (parent == NULL) {
parent = temp;
temp_parent = temp;
}
else {
link *current_parent;
temp_parent = parent;
while (temp_parent != NULL) {
current_parent = temp_parent;
if (v < temp_parent->val)
temp_parent = temp_parent->left;
else temp_parent = temp_parent->right;
}
if (temp->val < current_parent->val)
current_parent->left = temp;
else current_parent->right = temp;
}
}
void print__ (link *x) {
if (x == NULL) return ;
cout << x->val << endl;
print__ (x->left);
print__ (x->right);
}
int main () {
int n; cin >> n;
for (int i = 0 ; i < n; i++) {
int x; cin >> x;
Insert (x);
}
print__ (parent);
}