Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Basic question in binary tree node insertion

1 view
Skip to first unread message

Indrajeet

unread,
Oct 11, 2009, 1:47:14 PM10/11/09
to
I was looking at this function segment that inserts a node into a
binary tree :

void insert(Tree** pRoot, int n)
{
if (*pRoot != NULL)
{
if ((*pRoot)->val > n)
insert(&((*pRoot)->left),n);
else
insert(&((*pRoot)->right),n);
}
else
{
Tree* new = (Tree *)malloc(sizeof(Tree*));
new->val = n;
new->left = NULL;
new->right = NULL;
*pRoot = new;
}
}

main() makes successive calls to insert as in insert(&root,35); insert
(&root, 37); insert(&root, 39);
A preOrder listing as in preOrder(&root) prints correctly.

Since 39 is the last created node and the line in insert() goes
"*pRoot = new", would this not alter the variable root in main() to
point to the node that holds the last added value, viz. 39? Pardon me
if my understanding of pointers is fuzzy, I'd be much grateful for an
explanation showing where my understanding has got holes, obviously
I've got some way to go :)

-I
--
comp.lang.c.moderated - moderation address: cl...@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line. Sorry.

Dag-Erling Smørgrav

unread,
Oct 11, 2009, 3:14:28 PM10/11/09
to
Indrajeet <mummudi...@gmail.com> writes:
> [...]
> if (*pRoot != NULL) {
> /* ... */
> } else {
> /* ... */
> *pRoot = new;
> }
> [...]

> Since 39 is the last created node and the line in insert() goes
> "*pRoot = new", would this not alter the variable root in main() to
> point to the node that holds the last added value, viz. 39?

No, that line is only reached when the tree is empty.

DES
--
Dag-Erling Smørgrav - d...@des.no

tohava

unread,
Oct 11, 2009, 3:17:39 PM10/11/09
to
On Oct 11, 7:47 pm, Indrajeet <mummudichoz...@gmail.com> wrote:
> I was looking at this function segment that inserts a node into a
> binary tree :

Smells like homework

On Oct 11, 7:47 pm, Indrajeet <mummudichoz...@gmail.com> wrote:
>
> void insert(Tree** pRoot, int n)
> {
>     if (*pRoot != NULL)
>     {

> ...
>     }
>     else
>     {
> ...
>         *pRoot = new;


>      }
>
> }
>
> Since 39 is the last created node and the line in insert() goes
> "*pRoot = new", would this not alter the variable root in main() to
> point to the node that holds the last added value, viz. 39?

No, since the else-clause is never activated after the first call to
insert.

0 new messages