This repository has been archived by the owner on Jan 10, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_tree.txt
94 lines (88 loc) · 1.64 KB
/
binary_tree.txt
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
#include <iostream>
#include <map>
#include <string>
class Exception{};
class KeyError : public Exception{};
template<class K, class T>
class Node {
public:
Node* left;
Node* right;
Node* parent;
K key;
T data;
Node(K k, T d) : key(k), data(d), left(NULL), right(NULL){}
};
template <class K, class T>
class Tree {
Node<K, T>* root;
Node<K, T>* findNode(K k){
if (this->root){
if (this->root->key == k) {
return root;
}
Node<K, T>* next = root;
while (next && next->key != k) {
if (k < next->key) {
next = next->left;
}
else {
next = next->right;
}
}
if (next->key == k){
return next;
}
}
return NULL;
}
public:
Tree(): root(NULL) {};
bool add(K k, T d) {
if (this->root == NULL) {
this->root = new Node<K, T>(k, d);
return true;
}
else {
Node<K, T>* next = root;
for (;;) {
if (next->key == k) {
next->data = d;
return true;
}
if (k < next->key) {
if (next->left) {
next = next->left;
continue;
}
next->left = new Node<K, T>(k, d);
return true;
}
else {
if (next->right) {
next = next->right;
continue;
}
next->right = new Node<K, T>(k, d);
return true;
}
}
}
return false;
}
T find(K k) {
Node<K, T>* tmp = this->findNode(k);
if (tmp) {
return tmp->data;
}
else {
throw KeyError();
}
}
};
int main(){
Tree<int, int> t;
std::cout << t.add(5, 10) << t.add(7, 17) << t.add(3, 166) << t.add(2, 12) << std::endl;
std::cout << t.find(5) << std::endl;
return 0;
}