#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#define NDataType char
typedef struct BTNode
{
struct BTNode* left;
struct BTNode* right;
NDataType data;
}BT;
BT* BuyBTNode(NDataType x)
{
BT* tmp=(BT*)malloc(sizeof(BT));
assert(tmp);
tmp->data=x;
tmp->left=NULL;
tmp->right=NULL;
return tmp;
}
//先序遍历的顺序来创建二叉树
BT* CreateTree(char* parr,int* pi)
{
if(parr[*pi]=='#')
{
(*pi)++;
return NULL;
}
BT* root=BuyBTNode(parr[(*pi)++]);
root->left=CreateTree(parr, pi);
root->right=CreateTree(parr, pi);
return root;
}
void InOrder(BT* root)
{
if(root==NULL)
return;
InOrder(root->left);
printf("%c ",root->data);
InOrder(root->right);
}
int main()
{
char arr[100]={0};//数组存储字符串
scanf("%s",arr);//将输入的字符串存入数组
int i=0;
BT* root=CreateTree(arr,&i);//创建一个存根节点地址的指针,根据给出的数组创建树,返回根节点的地址。
InOrder(root);//中序遍历并打印
return 0;
}
[C题目]牛客KY11 二叉树遍历
于 2022-09-26 16:36:04 首次发布