Question: On your b-tree code, wouldn't the lh operand in the return recursively execute before the rh, throwing off the original reqs?
Asked by Will (24.234.85.x) on February 6 2013, 10:44pm
Reply on February 7 2013, 2:49am (edited at February 7 2013, 3:42am):Yes (it processes left before right), but no, it does what (as I understood, anyway) the requirements specified, since each top level call to the recursive function only prints a single level of the tree, so the left-to-rightness is what you want. Edit: here, this might be easier to understand (exact same function, just more clear code):
f(h, levelToPrint, currentLevel) {
if (currentLevel > levelToPrint) return 0;
if (!h) {
if (currentLevel == levelToPrint) print("(null)");
return 0;
}
if (currentLevel == levelToPrint) {
print(h);
return 1;
}
return f(h.left,levelToPrint, currentLevel+1) + f(h.right,levelToPrint, currentLevel+1);
}
levelToPrint=0;
while (f(tree,levelToPrint++,0)) print("\n");
Comment: