I think I would have done differently. First, I would simplify the other code a bit by adding ctor to the Node class:
struct Node{ Node *left; Node *right; T data; Node(T const &data) : left(nullptr), right(nullptr), data(data) {} };
Then you can use the pointer to the pointer to move through the tree and insert the element:
bool insert(const T value) { Node **pos; for (pos = &root; *pos != nullptr;) { if (value < (*pos)->value) pos = &(*pos)->left; else if ((*pos)->value < value ) pos = &(*pos)->right; else return false; } *pos = new Node(value); return true; }
Note that I delayed the creation of the new Node until we exit the loop. That way, if we have a repeating element, we can just go back (no leak node, since we haven't allocated a new Node yet).
What is it worth, if you are going to do it recursively, it would probably be easier to use a link to a pointer instead of a pointer to a pointer.
Jerry Coffin
source share