To begin with, this question is not a dup of this one, but builds on it.
Taking the tree in that question as an example,
1
/ \\
2 3
/
A version that doesn't require extra storage:
std::deque bfs;
bfs.push_back(start);
int nodesInThisLayer = 1;
int nodesInNextLayer = 0;
while (!bfs.empty()) {
Node front = bfs.front();
bfs.pop_front();
for (/*iterate over front's children*/) {
++nodesInNextLayer;
nodes.push_back(child);
}
std::cout << node.value;
if (0 == --nodesInThisLayer) {
std::cout << std::endl;
nodesInThisLayer = nodesInNextLayer;
nodesInNextLayer = 0;
} else {
std::cout << " ";
}
}
P.S. sorry for the C++ code, I'm not very fluent in Python yet.