7-1 前序序列创建二叉树
编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以二叉链表存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,代表一棵空树。然后再对二叉树进行中序遍历,输出遍历结果。
输入格式:
多组测试数据,每组测试数据一行,该行只有一个字符串,长度不超过100。
输出格式:
对于每组数据,
输出二叉树的中序遍历的序列,每个字符后面都有一个空格。
每组输出一行,对应输入的一行字符串。
输入样例:(及其对应的二叉树)
abc##de#g##f###
输出样例:
c b e g d f a
代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node *BinTree;
char str[110];
int i;
struct node
{char data;BinTree left;BinTree right;
};
BinTree CreatTree(BinTree T)
{char x;x=str[i++];if(x=='#')T=NULL;else{BinTree newnode=(BinTree)malloc(sizeof(struct node));newnode->left=newnode->right=NULL;newnode->data=x;T=newnode;T->left=CreatTree(T->left);T->right=CreatTree(T->right);}return T;
}
void print(BinTree T)
{if(T==NULL)return;else{print(T->left);printf("%c ",T->data);print(T->right);}
}
int main()
{while(scanf("%s",str)!=EOF){BinTree T=CreatTree(T);print(T);i=0;printf("\n");}return 0;
}
202206201631一