I have a binary tree that looks like this
struct Node
{
int key;
double data;
Node* right;
Node* left;
};
and I have this "insert" function for inserting new nodes and building the tree
void insert(Node*& p, int key, double to_be_inserted)
{
if (p == nullptr)
{
p = new Node;
p->key = key;
p->data = to_be_inserted;
p->left = nullptr;
p->right = nullptr;
}
else
{
if (p->key == key)
{
p->data = to_be_inserted;
}
else
{
Node*& newChild = (p->key > key) ? p->left : p->right;
insert(newChild, key, to_be_inserted);
}
}
}
and a main function that looks like this
int main(int argc, char ** argv)
{
Node* root = nullptr;
insert(root, 11, 11);
insert(root, 6, 6);
insert(root, 4, 4);
insert(root, 5, 5);
insert(root, 8, 8);
insert(root, 10, 10);
insert(root, 19, 19);
insert(root, 17, 17);
insert(root, 43, 43);
insert(root, 31, 31);
insert(root, 49, 49);
printTree(root, 0);
return 0;
}
The final "printed-out" tree looks like this
(This "print-out" is meant to be read from left to right instead of top to bottom)
What I don't understand is... when does the insert
function decide to backtrack (go back up the tree) and build a right subtree?
For example, if we look at insert(root, 5, 5)
and insert(root, 8, 8)
in main
, why does the 8
end up being a child node of node 6
instead of node 5
. According to the logic of the insert
function, it should just keep going down the tree and making the 8
a child node of node 5
... right?
I need help properly understanding the insert function. I am sure that I am misunderstanding something in it's logic.
Thanks (and sorry for the long post)!