0

please explain the working of following code? i am unable to get the recursion.

int depth(struct tree *q)
{ 
    int h1,h2;
    if(q==NULL)
       return 0;
    else
    {
       h1=depth(q->left);
       h2=depth(q->right);
    }
    return (max(h1,h2) +1 );
}

how does recursion work in the above code? how does h1 and h2 get there value?

  • 1
    The code will generate at least a warning, since there is a `return` statement that doesn't return anything. – Some programmer dude Aug 01 '12 at 10:43
  • i might have forgot that! my concern is that how recursion works! – user1553924 Aug 01 '12 at 10:44
  • 2
    As for how it works, I suggest you "execute" this on paper for a simple tree, writing down the variable values. – Some programmer dude Aug 01 '12 at 10:45
  • 2
    "To understand recursion, you must first understand recursion." http://stackoverflow.com/questions/717725/understanding-recursion – Karoly Horvath Aug 01 '12 at 10:46
  • Errm, where did you get the code? I presume you did not write it yourself, else you might hope to understand how it works. IF you got it elsewhere, was there no explanation? Can you contact the authour? Must you understand *this* piece of code, or are you just trying to grok recursion in general? (in which case google will show you many, many, many good explanations of recursion). What are you you hoping to achieve here? – Mawg says reinstate Monica Aug 01 '12 at 10:51

1 Answers1

4

Imagine a simple tree with only 3 nodes, 1 root and 2 children

      Node R
     /      \
    /        \
Node A      Node B

The first call to depth takes Node R as it's argument.

Call 1) q is not NULL so depth() is called for Node R left == Node A

Call 2) q is not NULL so depth() is called for Node A left == NULL

Call 3) q is NULL so return 0;

Call 2) h1 = 0; Now call for Node A right = NULL

Call 4) q is NULL so return 0;

Call 2) h1 = 0; h2 = 0; return max(0, 0) + 1

Call 1) h1 = 1; Now call for Node R right = Node B

Call 5) q is not NULL so depth() is called for Node B left == NULL

Call 6) q is NULL so return 0;

Call 5) h1 = 0; Now call for Node B right = NULL

Call 7) q is NULL so return 0;

Call 5) h1 = 0; h2 = 0; return max(0, 0) + 1;

Call 1) h1 = 1; h2 = 1; return max(1, 1) + 1;

Returns 2.

SpacedMonkey
  • 2,725
  • 1
  • 16
  • 17