c - Confused in understanding recursion -


i little bit confused following code to find height of tree , code find sum of n nos recursively, below this. lheight , rheight store, depending on number of recursions makes?

int height(struct node* node) {    if (node==null)        return 0;    else    {      lheight = height(node->left);      rheight = height(node->right);      if (lheight > rheight)          return(lheight+1);      else return(rheight+1);         } } 

here 1 more clarification, prints sum of n nos:

int findsum(int n){     int sum;     if(n <= 0) return 0;     else sum = n + findsum(n-1);     return sum; } 

if change to:

int findsum(int n){     int sum;     if(n <= 0) return 0;     else sum = findsum(n-1); // here     return sum; } 

it prints output 0. why doesn't return number of recursions, if above tree code does?

your second recursion equivalent to

sum = findsum(n-1) = findsum(n-2) = findsum(n-3) = ..... = findsum(0) = 0; 

if want second recursion return number of recursion use

sum = 1 + findsum(n-1); 

the lheight , rheight return tree level because in recursion function there incrementation 1 both variables:

     return(lheight+1);  else return(rheight+1);      

if want findsum() samething height() recusrsion should return sum+1 , not sum @ end of findsum() function:

int findsum(int n){     int sum;     if(n <= 0) return 0;     else sum = findsum(n-1);     return sum+1; //<<<<< should return sum +1 did in height function } 

the return sum+1; evaluated if

findsum(n-1); findsum(n-2); findsum(n-3); ...findsum(0); called.

  • when findsum(0) called, return 0;
  • when findsum(1) called, execute sum=findsum(0) (so sum = 0) , return sum+1 (1);
  • when findsum(2) called, execute sum=findsum(1) (so sum = 1) , return sum+1 (2);
  • when findsum(3) called, execute sum=findsum(2) (so sum = 2) , return sum+1 (3);
  • .
  • .
  • .
  • when findsum(n) called, execute sum=findsum(n-1) (so sum = n-1) , return sum+1 (n);

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -