喜欢这个问题:Create and traverse a binary tree recursively in C。我使用指向create tree struct的指针。这些代码可以编译但不能从CreateTree()函数返回。
#include <stdio.h>
#include<stdio.h>
typedef char ElemType;
// Tree struct
typedef struct tree
{
ElemType data;
struct tree * lchild;
struct tree * rchild;
}TreeNode,* Tree;
void CreateTree(Tree* t)
{
char ch;
scanf("%c",&ch);
if ( ch == '#' ){
*t = NULL;
}
else
{
*t = (Tree)malloc(sizeof(TreeNode));
if ( !(*t) )
{
printf("memory allocate error!");
return ;
}
(*t)->data = ch;
CreateTree(&((*t)->lchild));
CreateTree(&((*t)->rchild));
}
return ;
}
int main()
{
Tree T = NULL;
printf("\nPlease input node in preorder way,'#'means NULL:");
CreateTree(&T);
}
答案 0 :(得分:0)
你的代码没有结束的原因是:输入的char不是flush,它会在进一步的迭代中使用。 刚刚添加了getchar(),它就可以了。
#include <stdio.h>
// Tree struct
typedef struct tree
{
char data;
struct tree * lchild;
struct tree * rchild;
}TreeNode,* Tree;
void CreateTree(Tree* t)
{
char ch;
scanf("%c",&ch);
if ( ch == '#' ){
*t = NULL;
**getchar();**
}
else
{
*t = (Tree)malloc(sizeof(TreeNode));
if ( !(*t) )
{
printf("memory allocate error!");
return ;
}
(*t)->data = ch;
**getchar();**
CreateTree(&((*t)->lchild));
CreateTree(&((*t)->rchild));
}
return ;
}
int main()
{
Tree T = NULL;
printf("\nPlease input node in preorder way,'#'means NULL:");
CreateTree(&T);
}