题目描述:
编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。
具体代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct BTNode
{
struct BTNode* _left;
struct BTNode* _right;
char _data;
}BTNode;
BTNode* CreateTree(char* str,int* pi)
{
if(str[*pi]=='#')
{
return NULL;
}
else
{
BTNode* root=(BTNode*)malloc(sizeof(BTNode));
root->_data=str[*pi];
(*pi)++;
root->_left=CreateTree(str,pi);
(*pi)++;
root->_right=CreateTree(str,pi);
return root;
}
}
void InOrder(BTNode* root)
{
if(root==NULL)
{
return ;
}
else
{
InOrder(root->_left);
printf("%c ",root->_data);
InOrder(root->_right);
}
}
int main()
{
char str[100]={0};
scanf("%s",str);
int i=0;
BTNode* tree=CreateTree(str,&i);
InOrder(tree);
return 0;
}