I use this bit of code to create a new node and insert it into a binary search tree. It inserts the root properly, the same with its first right and left children but anything after that seems to replace the already existing child.
For example:
7
2 15
If I insert 10 now it will replace 15 instead of becomming its left child.
Node * createNode(Element elem)
{
Node * newNode = new Node;
newNode->elem = elem;
newNode->left = nullptr;
newNode->right = nullptr;
newNode->parent = nullptr;
return newNode;
}
bool insertElem(BST & tree, Element elem)
{
Node * newNode = createNode(elem);
if (!tree.root)
{
tree.root = newNode;
return true;
}
else
{
return insertElem(newNode, tree.root);
}
}
bool insertElem(Node * node, Node * root)
{
if (node->elem.key == root->elem.key) return false; // already exists
if (node->elem.key > root->elem.key) // goes to the right
{
if (root->right) insertElem(node, root->right);
node->parent = root;
root->right = node;
return true;
}
if (node->elem.key < root->elem.key) // goes to the left
{
if (root->left) insertElem(node, root->left);
node->parent = root;
root->left = node;
return true;
}
return false;
}