954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Problem in inorder traversal in binary search tree ...?

void inorder(struct node *r)
{
    if(r!=NULL)
    {
        inorder(r->left);
        printf("\t %d",r->data);
        inorder(r->right);
    }
}


in the above code when the last element is reached i.e r->left becomes null
then when inorder(r->left) is called it will send a null value to the function
and if condition becomes false so the it'll come out of the function.

But the problem is that instead of coming out of the loop it executes the
printf("\t %d",r->data); statement when it comes to the last element.


Please explain me(if you don't understand the question plz read it twice i need your help)

Thanks

Rubinder singh
Newbie Poster
14 posts since Dec 2010
Reputation Points: 10
Solved Threads: 0
 

There's nothing wrong with your code, it's the conventional recursive inorder traversal. Perhaps if you explained what you expected to happen that differs from what actually happens, someone can help you change the code to meet your needs.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

But plz tell me the reason why this code is behaving unexpectedly ?

Rubinder singh
Newbie Poster
14 posts since Dec 2010
Reputation Points: 10
Solved Threads: 0
 

It is not behaving unexpectedly. When the "inorder(r->left)" is called for the last time with a NULL pointer, it indeed just returns without having executed the loop. Then, the programm just continues to the next statement, which in your case is the printf function.

mikrosfoititis
Junior Poster in Training
74 posts since Nov 2011
Reputation Points: 18
Solved Threads: 11
 
But plz tell me the reason why this code is behaving unexpectedly ?


Your expectations are wrong, so the code will behave unexpectedly for you. Duh.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

@mikrosfoititis thanks dude ..................

Rubinder singh
Newbie Poster
14 posts since Dec 2010
Reputation Points: 10
Solved Threads: 0
 

ur welcome :)

mikrosfoititis
Junior Poster in Training
74 posts since Nov 2011
Reputation Points: 18
Solved Threads: 11
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: