I’m defining a binary search tree class like this:
template <class T>
class BSTNode
{
public:
BSTNode(){
right = left = 0;
}
BSTNode(const T& el, BSTNode * l = 0, BSTNode * r = 0)
{
val = el; left = l; right = r;
}
T val;
BSTNode * right;
BSTNode * left;
};
template <class T>
class BST
{
public:
BST(){ root = 0;}
void Insert(const T& el);
private:
BSTNode<T> * root;
};
and I implement the Insert() function like this:
template <class T>
void BST<T>::Insert(const T& el)
{
bool bEqual = false;
BSTNode<T> * p = root;
while(p)
{
if(el == p->val)
{
bEqual = true;
return;
}
if(el < p->val)
{
// go left
p = p->left;
}
if(el > p->val)
{
// go right
p = p->right;
}
}
if(!p)
{
std::cout << "creating new node " << el << "\n";
p = new BSTNode<T>(el);
}
}
Why does the root pointer variable stay at 0, and not the address of the new object?
You never do
root = ?;in your code; also,p = new BSTNode<T>(el);leaks memory.My guess is that you wanted to
pto be a reference to pointer, so you could change the original pointer.But, in such case,
pis not-reassignable. You may want to check if pointer you assign topis null and just insert the new value in correct place (eg.p->left = new BSTNode<T>(el);) and reassignponly when given pointer is not null.I mean: