POJ 2255/递归:前序中序求后序

Sample Input
DBACEGF ABCDEFG

已知二叉树的前序遍历与后序遍历求后序遍历

算法:前序遍历时,第一位为根:D;找到中序中的D,则前面的ABC在左子树,右边的EFG在右子树,则后序为为左子树+右子树+根:solve(BAC,ABC)+solve(EGF,EFG)+D

#include <iostream>
#include <string>
using namespace std;
string solve(string pre,string mid){
	if(pre.length()==1)return pre;
	else if(pre.length()==0)return "";
	int m = mid.find(pre[0]);
	
	return solve(pre.substr(1,m),mid.substr(0,m))+solve(pre.substr(m+1),mid.substr(m+1))+pre[0];
}
int main(int argc, char* argv[])
{
	
	string pre,mid;
	while(cin>>pre>>mid){
		
		cout<<solve(pre,mid)<<endl;
	}
	return 0;
}
posted on 2011-06-05 20:17  yangyh  阅读(367)  评论(1编辑  收藏  举报