编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以二叉链表存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,代表一棵空树。然后再对二叉树进行中序遍历,输出遍历结果。
输入格式:
多组测试数据,每组测试数据一行,该行只有一个字符串,长度不超过100。
输出格式:
对于每组数据,
输出二叉树的中序遍历的序列,每个字符后面都有一个空格。
每组输出一行,对应输入的一行字符串。
输入样例:(及其对应的二叉树)
abc##de#g##f###
输出样例:
c b e g d f a
代码:
//一看到'#'我就想到用栈,按前序顺序存储,再按中序遍历输出,遇到字符就入栈,遇到'#'出栈
#include <bits/stdc++.h>
using namespace std;
int main()
{
char a[10005];
stack <char> s;
while(~scanf("%s",a))
{
int i=0;
for(i=0;a[i]!='\0';i++)
{
if(a[i]=='#'&&!s.empty()){
printf("%c ",s.top());
s.pop();
}
else s.push(a[i]);
}
while(!s.empty())
{
if(s.top()!='#')
printf("%c ",s.top());
s.pop();
}
printf("\n");
}
}
还可以直接从树的定义出发
//其实思路挺简单的,一个创建树函数,一个中序遍历函数就搞定
#include <bits/stdc++.h>
using namespace std;
typedef struct TreeNode* BinTree;
typedef char ElemType;
struct TreeNode
{
ElemType Data;
BinTree left;
BinTree right;
};
int i=0;
char str[105];
BinTree CreateBinTree(){
if(str[i]=='#'){
i++;
return NULL;
}
BinTree T=(BinTree)malloc(sizeof(struct TreeNode));
T->Data=str[i];
i++;
T->left=CreateBinTree();
T->right=CreateBinTree();
return T;
}
void InorderTraversal(BinTree T)
{
if(T){
InorderTraversal(T->left);
printf("%c ",T->Data);
InorderTraversal(T->right);
}
}
int main()
{
while(~scanf("%s",str))
{
BinTree T=CreateBinTree();
InorderTraversal(T);
cout<<endl;
i=0; //注意i要重置
}
}