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
| #include <iostream>
using namespace std;
struct treeNode {
int val;
int position;
treeNode* left;
treeNode* right;
treeNode(int val,int position){
this->val = val;
this->position = position;
this->left = nullptr;
this->right = nullptr;
}
};
class BinarySearchTree {
treeNode* root = nullptr;
void add(int value,int position,treeNode* node){
if (node==nullptr) {
throw "树为空";
}
if (value == node->val) {
return;
}else if(value < node->val){
if (node->left==nullptr) {
node->left = new treeNode(value,position);
}else{
add(value, position, node->left);
}
}else{
if (node->right==nullptr) {
node->right = new treeNode(value,position);
}else{
add(value, position, node->right);
}
}
}
int search(int keyValue,treeNode* node){
if (node==nullptr) {
return -1;
}else if(keyValue < node->val){
return search(keyValue, node->left);
}else if(keyValue > node->val){
return search(keyValue, node->right);
}else{
return node->position;
}
}
public:
/**
*添加结点
**/
void add(int value,int position){
if (root==nullptr) {
root = new treeNode(value,position);
}else{
add(value, position, root);
}
}
/**
*搜索
**/
int search(int keyValue){
return search(keyValue, root);
}
};
int main(int argc, const char * argv[]) {
int a[] = {4,6,3,5,7,2,9,8,10};
BinarySearchTree* tree = new BinarySearchTree();
for (int i=0; i<9; i++) {
tree->add(a[i], i);
}
for (int i=0; i<20; i++) {
cout<<tree->search(i)<<endl;
}
return 0;
}
|