0
int Size(struct node* node)
{
   if(node == NULL)
   {
      return 0;
   }
   else if(node != NULL)
   {
      return (Size(node->left) + 1 + Size(node->right));
   }
}

Hi, can anybody please post the stack trace for the following piece of code.

Lets say if we insert the values 2, 1, 10, 5... Then what could be the stack representation during the recursion process.. Please, its very urgent, and its very confusing too...

abatishchev
  • 98,240
  • 88
  • 296
  • 433
AGeek
  • 5,165
  • 16
  • 56
  • 72
  • 9
    You won't learn anything if we do your homework for you. – Yacoby May 09 '10 at 09:37
  • Well Sir, its not a HW. i am just trying to make a program to calculate the size of the tree.. How many elements are there in the Tree. And with some internet help, i found out this piece of code, which looks pretty easy, but i am trying to understand it, but little bit of fuzzy concepts in recursion.. – AGeek May 09 '10 at 09:43
  • Plz if any body can make ths code, little bit understanding, thn i vl be highly obliged.. Thankx.. – AGeek May 09 '10 at 09:44
  • aree with above. use debugger(your ide internal debugger or gdb), and read this http://en.wikipedia.org/wiki/Nested_set_model – Maksim Burnin May 09 '10 at 09:44
  • Sir, i tried installing gdb on my Fedora machine.. But it throws some errors at the end during MAKE command.. i have posted one question on the same on stackoverflow,, but no replies.....http://stackoverflow.com/questions/2792912/not-able-to-install-gdb-on-fedora..... – AGeek May 09 '10 at 09:49

2 Answers2

2

Why not simply use printf? One when entering and one when leaving the function:

int Size(struct node* node)
{
    printf("Enter %d\n", ( node ? node->value : -1 ));
    ...
    printf("Leave %d\n", ( node ? node->value : -1 ));
}
Secure
  • 4,268
  • 1
  • 18
  • 16
  • This idea is pretty kool.. but where to put this "Leave" printf statement, in my code.. I want to understand the flow of the programm that i have posted.. plz little bit guidance..:-) Anyways Thankx for that idea..:-) – AGeek May 09 '10 at 10:30
  • Put it before each return. You have to restructure the function a bit and use a temporary variable for the second return, of course. Since you're already working with recursion, I'm sure you know how to do this. And be prepared to answer the question what the ?: is doing when your tutor asks you about it. Or instead use ifs to check the NULL case. – Secure May 09 '10 at 11:18
  • Hmm thnx for the reply.. I am working in an IT Company, and just improving upong my data structure concepts,, so no point comes of tutor as such!! Anywayz thanx a lot for that stuff.. :-) Keep Rocking!! – AGeek May 09 '10 at 13:01
0

Try using gdb and see the backtrace/bt command for gdb.

Karan
  • 12,724
  • 6
  • 40
  • 33