#####题目
UVA 536
#####AC code
#include"cstdio"
#include"iostream"
#include"stack"
#include"string"
using namespace std;
string pre,ino;
int L[30],R[30];
stack<char> st;
int build(int l1, int r1, int l2, int r2){
if(l1>r1) return 0;
char root=pre[l1];
st.push(root);
int p=l2;
while(ino[p]!=root) p++;
int cn = p-l2;
build(l1+cn+1, r1, p+1, r2);
build(l1+1, l1+cn, l2, p-1);
return 0;
}
int main(){
char root;
while(cin>>pre>>ino){
int r1=pre.length() -1;
int r2=ino.length() -1;
L[30]={0};
R[30]={0};
while(!st.empty())
st.pop();
build(0, r1, 0, r2);
while(!st.empty()){
printf("%c",st.top());
st.pop();
}
printf("\n");
}
return 0;
}
- 刚开始思路是,先建树,再后序DFS ——没有成功
- 参考大神报告,发现自己建树的过程就可以按照(根——>右子树——>左子树)递归,把根存入到栈里面,再输出即为后序遍历——成功!
同理:由后序和中序求先序,可以说是同样的方法;只不过建树的过程按照(根——>左子树——>右子树)递归,依次输出根即为先序遍历!