输入一个二叉树的先序遍历,请输出中序遍历和后序遍历。
二叉树的左右子节点必须全部输入,如果没有,请用 '.' 代替。
【样例输入】
ABC..DE...F.G..
【样例输出】
CBEDAFG
CEDBGFA
code:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll m=7;
struct node;
typedef node* tree;
struct node{
char data;
tree lchild;
tree rchild;
};
inline ll read(){
ll k=0;char ch=getchar();
while(!isdigit(ch))ch=getchar();
while(isdigit(ch))k=(k<<1)+(k<<3)+(ch^48),ch=getchar();
return k;
}
void build(tree &bt){//输入先序遍历
char ch;
ch=getchar();
if(ch!='.'){
bt= new node;
bt->data=ch;
build(bt->lchild);
build(bt->rchild);
}
else bt=NULL;
}
void preorder(tree bt){//先序遍历
if(bt){
cout<<bt->data;
preorder(bt->lchild);
preorder(bt->rchild);
}
}
void preorder2(tree bt){//中序遍历
if(bt){
preorder(bt->lchild);
cout<<bt->data;
preorder(bt->rchild);
}
}
void preorder3(tree bt){//后序遍历
if(bt){
preorder(bt->lchild);
preorder(bt->rchild);
cout<<bt->data;
}
}
int main(){
tree bt=NULL;
build(bt);
// preorder(bt);
// cout<<'\n';
preorder2(bt);
cout<<'\n';
preorder3(bt);
return 0;
}