思路:分治思想,递归构建二叉树,构建二叉树先malloc出根节点然后再构建左子树,右子树即可。因为字符串需要构建之后指针向后移动找到下一个字符,所以需要一个count指针标记字符位置,构建之后指针向后移动,指针指向’#‘或者'\0'代表到了空节点了完成返回NULL即可
构建完成之后就中序遍历就好。
#include<stdio.h>
typedef struct TreeNode
{
char val;
struct TreeNode* left;
struct TreeNode* right;
}TreeNode;
TreeNode* maketree(char*arr,int*count)
{
if(arr[*count]=='#'||arr[*count]=='\0')
{
return NULL;
}
TreeNode* newnode = (TreeNode*)malloc(sizeof(TreeNode));
newnode->val = arr[(*count)++];
newnode->left = maketree(arr,count);
(*count)++;
newnode->right = maketree(arr,count);
return newnode;
}
void Inorder(TreeNode* root)
{
if(root==NULL)
{
return;
}
Inorder(root->left);
printf("%c ",root->val);
Inorder(root->right);
}
int main()
{
char arr[101];
scanf("%s",arr);
int count = 0;
TreeNode* tree = maketree(arr,&count);
Inorder(tree);
return 0;
}