遍历二叉树
#include <stdio.h>
//定义二叉树结构
typedef struct TreeNode
{
char val;
struct TreeNode* left;
struct TreeNode* right;
}TreeNode;
//创建前序二叉树
TreeNode* CreatTree(char* str,int *pi)
{
if(str[*pi]=='#')
{
(*pi)++;
return NULL;
}
else
{
TreeNode* root=(TreeNode*)malloc(sizeof(TreeNode));
root->val=str[*pi];
(*pi)++;
root->left=CreatTree(str,pi);
root->right=CreatTree(str,pi);
return root;
}
}
//打印中序二叉树
void InOrder(TreeNode* root)
{
if(root==NULL)
{
return;
}
InOrder(root->left);
printf("%c ",root->val);
InOrder(root->right);
}
int main() {
char str[100];
scanf("%s",str);//输入字符
int i=0;
TreeNode* root=CreatTree(str,&i);//把字符放入二叉树
InOrder(root);
return 0;
}