You can do this by repeatedly traversing the tree in turn when printing only those nodes at a specified level. However, this is not strictly read-only memory, since recursion uses a call stack. And it is super inefficient. Like O (n * 2 ^ n) or something like that.
printLevel = 1;
while(moreLevels) {
moreLevels = printLevel(root, 1, printLevel);
printLevel++;
}
boolean printLevel(Node node, int currentLevel, int printLevel) {
boolean moreLevels = false;
if(node == null) {
return(false);
}
else if(currentLevel == printLevel) {
print the node value;
}
else {
moreLevels |= printLevel(node.leftChild, currentLevel + 1, printLevel);
moreLevels |= printLevel(node.rightChild, currentLevel + 1, printLevel);
}
return(moreLevels);
}
Cubby source
share