题目:
思路:这道题的主要问题是怎么创建题目所描述的二叉树,这里所采取的做法是:类似前序遍历,遇到 ’#‘ 就返回,其它字母就创建一个结点,然后向左递归,然后向右递归,最后返回就可以了。
代码:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<assert.h>
#include<stdbool.h>
typedef char BTdatatype;
typedef struct BinaryTreeNode {
BTdatatype data;
struct BinaryTreeNode* left;
struct BinaryTreeNode* right;
}BTNode;
BTNode* buyNode(BTdatatype x)
{
BTNode* newnode = (BTNode*)malloc(sizeof(BTNode));
assert(newnode);
newnode->data = x;
newnode->left = newnode->right = NULL;
return newnode;
}
BTNode* CreatTree(char* ch, int* pi)
{
if(ch[*pi] == '#')
{
(*pi)++;
return NULL;
}
BTNode* root = buyNode(ch[(*pi)++]);
root->left = CreatTree(ch, pi);
root->right = CreatTree(ch, pi);
return root;
}
void inorder(BTNode* root)
{
if(root == NULL)
return;
inorder(root->left);
printf("%c ", root->data);
inorder(root->right);
}
int main() {
char ch[150];
int i = 0;
scanf("%s", ch);
BTNode* root = CreatTree(ch, &i);
inorder(root);
return 0;
}