I think where I'm stuck is when we reach base case, we:
return p_new_tree;
which let's say currently the root is 80, 29, 28.
So we go left and node 28->left would be p_new_tree (pointer to this new node)
which is what this does
1 2
|
if( key < p_tree->key_value )
p_tree->p_left = insert( p_tree->p_left, key )//so p_new_tree returned to the current p_tree->left and p_tree currently is node 28
|
, ok I forgot about the the last line in the function:
return p_tree;//so this means currently we are @ node 28 so we return node 28 back to the previous left subtree recursive call
so we return pointer to node 28 to:
1 2
|
if( key < p_tree->key_value )
p_tree->p_left = insert( p_tree->p_left, key )
|
again, and then
return p_tree;
where now
p_tree is node 29 which gets returned to the previous left subtree recursive call so again: I think where I'm stuck is when we reach base case, we:
return p_new_tree;
which let's say currently the root is 80, 29, 28.
So we go left and node 28->left would be p_new_tree (pointer to this new node)
which is what this does
1 2
|
if( key < p_tree->key_value )
p_tree->p_left = insert( p_tree->p_left, key )//so p_new_tree returned to the current p_tree->left and p_tree currently is node 28
|
, ok I forgot about the the last line in the function:
return p_tree;//so this means currently we are @ node 28 so we return node 28 back to the previous left subtree recursive call
so we return pointer to node 28 to:
1 2
|
if( key < p_tree->key_value )
p_tree->p_left = insert( p_tree->p_left, key )
|
again, and then
return p_tree;
where now
p_tree
and NOW p_tree is node 80 which points to node 29. I hope that is correct. I think it was forgetting about that last line
return p_tree;
at the end of the function that threw me off.
Put simply: What you return is what you get back. Just like what you put in is exactly what you get in return...I just forgot about what is being returned, so initially once base case reached, indeede p_new_tree is returned, BUT then onwards it's p_tree being returned so the pointer to the new node (p_new_tree) is being returned and assigned to the previous caller's p_tree->left and so forth, so each level has their own p_tree->left that we return back all the way to main. Because a stack frame stores independently its own version of the pointer
p_tree so when we
return p_tree
, it goes back to whoever called it but it's different than my return_when_one function where the SAME value returned back to main b/c I am setting p_tree->left = insert(p_tree->left) for e.g. and THIS p_tree will be returned. I think that's right.