二叉树遍历
题目描述:
编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。
题目来源:牛客
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode
{
struct TreeNode* left;
struct TreeNode* right;
char val;
}TreeNode;
TreeNode* CreateTree(char* str,int* i)
{
if(str[*i] == '#')
{
(*i)++;
return NULL;
}
//不是#,构造根
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = str[*i];
(*i)++;
//递归构建左子树
root->left = CreateTree( str, i);
//递归构建右子树
root->right = CreateTree( str, i);
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 = CreateTree(str,&i);
Inorder(root);
printf("\n");
return 0;
}