题目为:
程序如下:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct bnode_type
{
char data;
struct bnode_type *leftchild;
struct bnode_type *rightchild;
}bnodetype;
void input(bnodetype **root);
bool memorytest(bnodetype *node);
void preorder(bnodetype *root);
int main(void)
{
bnodetype *root;
root= NULL;
input(&root);
printf("The tree is\n");
preorder(root);
printf("\n");
return 0;
}
bool memorytest(bnodetype *node)
{
if (node == NULL)
exit(EXIT_FAILURE);
return true;
}
void input(bnodetype **root)
{
char data;
if (*root == NULL)
{
data = getchar();
if (data == ' ' || data == '\n')
return ;
*root = (bnodetype *)malloc(sizeof(bnodetype));
memorytest(*root);
(*root)->data = data;
(*root)->leftchild = NULL;
(*root)->rightchild = NULL;
}
if ((*root)->leftchild == NULL)
input(&(*root)->leftchild);
if ((*root)->rightchild == NULL)
input(&(*root)->rightchild);
}
void preorder(bnodetype *root)
{
if (root != NULL)
{
printf("%c", root->data);
preorder(root->leftchild);
preorder(root->rightchild);
}
}
运行效果如下: