I'm trying to define a set of template classes to represent search trees in C++.
In the find method i need to return the pointer of the node (represent as a pointer) that cointains the given key; in this way I'll reuse find method to implement insertion and deletion.
template <class K, class R>
struct Node {
K key;
R record;
inline Node(K k, R r) {
this->key = k;
this->record = r;
}
};
template <class K, class R>
struct BST_Node : public Node<K,R> {
BST_Node<K,R> *sx;
BST_Node<K,R> *dx;
inline BST_Node(K key, R record)
: Node<K,R>(key, record) {
this->sx = NULL;
this->dx = NULL;
}
BST_Node<K,R> **find(K k) {
BST_Node<K,R> **p = k < this->key ? &this->sx : &this->dx;
while (*p && k != (*p)->key)
p = k < (*p)->key ? &(*p)->sx : &(*p)->dx;
return p;
}
/* other methods */
};
There is just a little problem: what if the key is in the root?
I cannot return &this because this, so what can I do?
The reason because i want to use pointer to pointer is that in this way I can return the address of a NULL pointer, so for insertion I can write something like that:
BST_Node<K,R> *insert(K k, R r) {
BST_Node<K,R> **p = this->find(k);
if (*p == NULL) //if the search fails
*p = new BST_Node<K,R>(k, r);
return *p;
}