I try to write a function which prints all the paths from the root node to the leaf nodes.
- print the nodes in the order from the root to the leaf
- for every node left child comes before right child
- put spaces after node values, including the last one
- end each path with a newline, including the last one
- if the root is NULL, do not print anything
For example;
printPaths(bt1);
>2_1_
>2_3_
for this example 2 is a root, and 1-3 are leaves.
Here is my simple code, I cannot find where should be new line because when I write printf("\n")
anywhere, it prints crazy outputs, so I could not find the problem in this code.
void printPaths(TreeNode* root) {
if(root != NULL) {
printf("%d ", root->val);
printPaths(root->left);
printPaths(root->right);
}
}