The ideas and algorithmic concepts exposed are more important here, than what technology you apply. That being said:
C++ Answer (easily portable to C#):
Assuming a classical Binary Tree structure similar to this:
struct node {
char data;
node* left;
node* right;
}
// Function to print each level in the tree*
void printByLevel(node* root) { // Copy root node, pass by value.
int height = height(root); // Get tree height. Total amount of levels to print.
for (int i = 1; i <= h; i++) {
printLevel(root, i);
std::cout << std::endl; // A line after each level is printed.
}
}
You will need the auxiliary function below, as well as function for computing your tree height to be able to execute the function above.
// Print nodes at ONE specific level
void printLevel(node* root, int level) { // Copy root node, pass by value.
if (root != nullptr) {
if (level == 1)
std::cout << root->data << ' ';
else if (level > 1) {
printLevel(root->left, level-1);
printLevel(root->right, level-1);
}
}
std::cout << "NULL" << ' '; // No value, print "NULL"
}
leaf?.ToString() ?? "NULL"