2323
2424#include < stdlib.h>
2525#include < stdint.h>
26+ #include < exception>
27+
2628namespace alg
2729{
2830template <typename KeyT, typename ValueT>
@@ -39,9 +41,19 @@ namespace alg
3941treeNode *left;// left child
4042treeNode *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
4354private:
4455treeNode * m_root;
56+ BSTException error;
4557
4658public:
4759BST ():m_root(NULL ){};
@@ -53,16 +65,36 @@ namespace alg
5365
5466ValueT operator [] (const KeyT & key)
5567{
56- if (m_root == NULL ) return NULL ;
68+ if (m_root == NULL ) throw error ;
5769treeNode * tmp = m_root;
5870
5971while (true ) {
6072if (key == tmp->key ) return tmp->value ;
6173else 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 ;
6395tmp = tmp->left ;
6496} else {
65- if (tmp->right == NULL ) return NULL ;
97+ if (tmp->right == NULL ) return false ;
6698tmp = tmp->right ;
6799}
68100}
0 commit comments