0

I am trying to print inorder, the data of a BST. This works with simple recursion, however I can not figure out how to print a newline at the end of the printed data, before the function returns to the calling code.

/* Print data for inorder tree traversal on single line,
 * separated with spaces, ending with newline. */

void printTree(struct TreeNode* root)
{
  if(root)
  {
    printTree(root->left);
    printf("%d ", root->data);
    printTree(root->right);
  }
}
Michael
  • 87
  • 8
  • just add `printf("\n");` at the end ? [mcve] is required – Stargateur Nov 10 '17 at 02:24
  • 1
    You can add `printf("\n");` statement just after calling `printTree()`. – H.S. Nov 10 '17 at 02:28
  • Please provide full information. Moreover, You can add a base case statement. And print newline after every leafnode. ( If this is what you're doing ) – Neha Nov 10 '17 at 02:30

3 Answers3

2

You can use a helper function to print a newline after all the recursive calls finish:

void printTreeHelper(struct TreeNode* root)
{
  if(root)
  {
    printTreeHelper(root->left);
    printf("%d ", root->data);
    printTreeHelper(root->right);
  }
}

void printTree(struct TreeNode *root)
{
    printTreeHelper(root);
    printf("\n");
}
MFisherKDX
  • 2,840
  • 3
  • 14
  • 25
0

The simplest way is you could just print a newline after calling the function.

Another simple way is to have two functions. The new function would be the first one that you would call. Then inside the new function, call the one you have implemented. After that, print a newline.

something like:

void TreePrinter(){
  PrintTree()
  print the newline
}
Antithesis
  • 161
  • 8
-1

You can write a macro, like this:

#define PRINT_NEWLINE_AFTER_CALL(x) x,printf("\n")

and use it like this:

PRINT_NEWLINE_AFTER_CALL(printTree(root));

If your function returns a value, with this macro you can receive that return value as well. Say, your function printTree() returns int then you can:

int retval = PRINT_NEWLINE_AFTER_CALL(printTree(root));
H.S.
  • 11,654
  • 2
  • 15
  • 32
  • I don't like it because it has problems. `if (y) PRINT_NEWLINE_AFTER_CALL(printTree(root));` doesn't work. If you *must* use a multi-line macro consider enclosing it in a `do...while(0)` loop. https://stackoverflow.com/questions/923822/whats-the-use-of-do-while0-when-we-define-a-macro – MFisherKDX Nov 11 '17 at 15:21
  • @MFisherKDX: I did not consider enclosing it in `do{..}while(0)` because the macro supposed to expand to a function call and if enclosed in `do{..}while(0)` then the return value of function cannot be received. I know that in the question asked, the return type of `printTree()` is `void` but I tried to write the macro in generalized way so that it can be used with a recursive function which returns some value. I have made correction, hope you like it. – H.S. Nov 11 '17 at 17:20