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, return0; - when
findsum(1)called, executesum=findsum(0)(sosum = 0) , returnsum+1(1); - when
findsum(2)called, executesum=findsum(1)(sosum = 1) , returnsum+1(2); - when
findsum(3)called, executesum=findsum(2)(sosum = 2) , returnsum+1(3); - .
- .
- .
- when
findsum(n)called, executesum=findsum(n-1)(sosum = n-1) , returnsum+1(n);
Comments
Post a Comment