I am currently trying to wrap my head around recursion so I picked a c++ textbook and began to read. The first couple of pages in the chapter on recursion were easy to understand but then I got to an item that doesn’t make sense to me.
int height(node *p)
{
if(p==NULL)
return 0;
else{
return 1 + max(height(p->llink),height(p->rlink));
}
If max gives me the greatest of two values, how does max get its arguments from what height it’s returning.
If anyone could help I would greatly appreciate it…..
To understand recursion you have to think recursively:
Starting from this you can trivially understand the code. If you draw the tree you will see what happens. If you have for example
height(A)will return1 + max(height(B), height(C))height(B)will return1 + max(height(D), height(E))height(C)will return1 + max(height(NULL), height(NULL)) = 1height(D)will return1 + max(height(NULL), height(NULL)) = 1height(E)will return1 + max(height(NULL), height(NULL)) = 1so
(I omitted calls to
height(NULL)because they are trivially 0 and otherwise it would have been too much verbose.)