代码:
#include <stdio.h>
#include <stdlib.h>
//创建二叉链节点的结构
typedef struct BinaryTreeNode
{
char val;
struct BinaryTreeNode* left;
struct BinaryTreeNode* right;
}BTNode;
//申请节点
BTNode* BuyNode(char str)
{
BTNode* newnode = (BTNode*)malloc(sizeof(BTNode));
if(newnode == NULL)
{
perror("malloc error!\n");
exit(1);
}
newnode->val = str;
newnode->left = newnode->right = NULL;
return newnode;
}
//建二叉树
BTNode* BinaryTreeCreate(char* a, int* pi)
{
if(*(a+(*pi)) == '#')
{
(*pi)++;
return NULL;
}
//申请节点
BTNode* root = BuyNode(*(a+(*pi)++));
root->left = BinaryTreeCreate(a,pi);
root->right = BinaryTreeCreate(a,pi);
return root;
}
//中序遍历
void InOrder(BTNode* root)
{
if(root == NULL)
{
return;
}
InOrder(root->left);
printf("%c ",root->val);
InOrder(root->right);
}
int main() {
char ch[100] = {'\0'};
//用户输入
scanf("%s",ch);
int i = 0;
InOrder(BinaryTreeCreate(ch, &i));
return 0;
}