Skip to content

Commit a04a2b2

Browse files
committed
change bst interface
1 parent 79b0f75 commit a04a2b2

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

include/binary_search_tree.h

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323

2424
#include <stdlib.h>
2525
#include <stdint.h>
26+
#include <exception>
27+
2628
namespace alg
2729
{
2830
template<typename KeyT, typename ValueT>
@@ -39,9 +41,19 @@ namespace alg
3941
treeNode *left;// left child
4042
treeNode *right;// right child
4143
};
44+
45+
class BSTException: public std::exception
46+
{
47+
public:
48+
virtual const char * what() const throw()
49+
{
50+
return "key does not exist";
51+
}
52+
};
4253

4354
private:
4455
treeNode * m_root;
56+
BSTException error;
4557

4658
public:
4759
BST():m_root(NULL){};
@@ -53,16 +65,36 @@ namespace alg
5365

5466
ValueT operator[] (const KeyT & key)
5567
{
56-
if (m_root == NULL) return NULL;
68+
if (m_root == NULL) throw error;
5769
treeNode * tmp = m_root;
5870

5971
while(true) {
6072
if (key == tmp->key) return tmp->value;
6173
else if(key < tmp->key) {
62-
if (tmp->left == NULL) return NULL;
74+
if (tmp->left == NULL) throw error;
75+
tmp = tmp->left;
76+
} else {
77+
if (tmp->right == NULL) throw error;
78+
tmp = tmp->right;
79+
}
80+
}
81+
}
82+
83+
/**
84+
* test whether the key is in the tree
85+
*/
86+
bool contains(const KeyT & key)
87+
{
88+
if (m_root == NULL) return false;
89+
treeNode * tmp = m_root;
90+
91+
while(true) {
92+
if (key == tmp->key) return true;
93+
else if(key < tmp->key) {
94+
if (tmp->left == NULL) return false;
6395
tmp = tmp->left;
6496
} else {
65-
if (tmp->right == NULL) return NULL;
97+
if (tmp->right == NULL) return false;
6698
tmp = tmp->right;
6799
}
68100
}

src/binary_search_tree_demo.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,11 @@ int main()
3030
for(i = 0; i < MAX_ELEMENTS; i++){
3131
printf("getting %d->%d\n",key[i], t[key[i]]);
3232
}
33+
34+
for(i = 0; i < MAX_ELEMENTS; i++){
35+
int k = rand()%100;
36+
printf("testing %d-> %s\n",k,t.contains(k)?"YES":"NO");
37+
}
38+
3339
return 0;
3440
}

0 commit comments

Comments
 (0)