Problem Description
已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并按中序和后序的方式遍历该二叉树。
Input
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output
每组输入数据对应输出2行:
第1行输出中序遍历序列;
第2行输出后序遍历序列。
Example Input
abc,,de,g,,f,,,
Example Output
cbegdfa
cgefdba
遍历即将树的所有结点访问且仅访问一次。按照根节点位置的不同分为前序遍历,中序遍历,后序遍历。
前序遍历:根节点->左子树->右子树
中序遍历:左子树->根节点->右子树
后序遍历:左子树->右子树->根节点
例如:求下面树的三种遍历
前序遍历:abdefgc
中序遍历:debgfac
后序遍历:edgfbca
#include <bits/stdc++.h>
using namespace std;
char a[55];
int l;
typedef struct tnode
{
char data;
struct tnode *lc,*rc;
}*tree;
tree create()
{
tree t;
char c;
c=a[l++];
if(c==','){
t=NULL;
}
else {
t=new(tnode);
t->data=c;
t->lc=create();
t->rc=create();
}
return t;
}
void zhongxu(tree t)
{
if(t){
zhongxu(t->lc);
cout<<t->data;
zhongxu(t->rc);
}
}
void houxu(tree t)
{
if(t){
houxu(t->lc);
houxu(t->rc);
cout<<t->data;
}
}
int main()
{
while(cin>>a){
tree t;
l=0;
t=create();
zhongxu(t);
cout<<endl;
houxu(t);
cout<<endl;
}
return 0;
}