2

Is there a way for me to print a binary tree level by level while displaying a NULL every time there is an empty node?

For example, let's say we have this tree:

And the output should look like this:

A
B C
D NULL E F

How should I go about writing the code to produce said output with the tree? Thanks in advance. This is my first post here. Sorry if the formatting and syntax is off.

1
  • You don't show any code for us to help you modify. I would just use the null coleascing operator: leaf?.ToString() ?? "NULL" Commented Mar 30, 2017 at 0:06

1 Answer 1

2

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"
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.