Since you showed your own efforts first, I shall.
Code:
void nodesprintHier(Treeptr p)
{
if (p->right == NULL && p->left == NULL) {
printf("%d", p->value);
return;
}
printf("(%d ", p->value);
if (p->left == NULL)
printf("[]");
else
nodesprintHier(p->left);
printf(" ");
if (p->right == NULL)
printf("[]");
else
nodesprintHier(p->right);
printf(")");
}
The nodesprintHier() function first checks if both leaves are NULL, and if so, it just prints the value of the current node and returns.
When at least one node is non-NULL, it prints an open parens (, the value of the current node, and a space.
If the left node is NULL, the function prints the null marker. Otherwise it uses a recursive call to print the value of the left subtree.
The function then prints the space.
If the right node is NULL, the function prints the null marker. Otherwise it uses a recursive call to print the value of the right subtree.
Finally, the function prints the close parens ), after which it is done.
Onwards:
Code:
void treeprintHier(Treeptr p)
{
printf("(%d ", p->value);
if (p->left == NULL)
printf("[]");
else
nodesprintHier(p->left);
printf(" ");
if (p->right == NULL)
printf("[]");
else
nodesprintHier(p->right);
printf(")\n");
}
If you look closely, the treeprintHier() function is almost a perfect duplicate, except it omits the initial check -- therefore always printing both leaves, even if one or both are NULL --, and prints a newline after the final close parens. If the left and/or right are not NULL, it uses nodesprintHier() to print them recursively.
If you use treeprintHier() to print out your trees, you will always get one line of output, in parentheses. If you use nodesprintHier() to print a tree with only the root node, you only get a plain number without any parentheses.
_ _ _ _ _
Now, say you occasionally want to print your trees to a file.
You rewrite the functions to take a stream handle, say into
Code:
static void fprintnode(FILE *const out, Treeptr p)
{
if (p->right == NULL && p->left == NULL) {
fprintf(out, "%d", p->value);
return;
}
fprintf(out, "(%d ", p->value);
if (p->left == NULL) {
fputs("[] ", out);
} else {
fprintnode(out, p->left);
fputc(' ', out);
}
if (p->right == NULL) {
fputs("[])", out);
} else {
fprintnode(out, p->right);
fputc(')', out);
}
}
void fprinttree(FILE *const out, Treeptr p)
{
fprintf(out, "(%d ", p->value);
if (p->left == NULL) {
fputs("[] ", out);
} else {
fprintnode(out, p->left);
fputc(' ', out);
}
if (p->right == NULL) {
fputs("[])\n", out);
} else {
fprintnode(out, p->right);
fputs(")\n", out);
}
}
and replace your original functions with wrappers:
Code:
void treeprintHier(Treeptr p)
{
fprinttree(stdout, p);
}
void nodesprintHier(Treeptr p)
{
fprintnode(stdout, p);
}
Does my suggestions make more sense now that you see the actual code?