c++ - How Recursion Works Inside a For Loop -
i new recursion , trying understand code snippet. i'm studying exam, , "reviewer" found standford' cis education library (from binary trees nick parlante).
i understand concept, when we're recursing inside loop, blows! please me. thank you.
counttrees() solution (c/c++)
/* key values 1...numkeys, how many structurally unique binary search trees possible store keys. strategy: consider each value root. recursively find size of left , right subtrees. */ int counttrees(int numkeys) { if (numkeys <=1) { return(1); } // there 1 value @ root, whatever remains // on left , right each forming own subtrees. // iterate through values root... int sum = 0; int left, right, root; (root=1; root<=numkeys; root++) { left = counttrees(root - 1); right = counttrees(numkeys - root); // number of possible trees root == left*right sum += left*right; } return(sum); }
imagine loop being put "on pause" while go in function call.
just because function happens recursive call, works same function call within loop.
the new recursive call starts it's for
loop , again, pauses while calling functions again, , on.
Comments
Post a Comment