PAT甲级1020 Tree Traversals

1020 Tree Traversals (25分)

思路:层序遍历的变形,用队列存储左右子树,只不过这个左右子树是根据后序和中序推导得到的;

#include
using namespace std;

vector<int> level;
void tolevel(vector<int> post,vector<int> in){
	queue<vector<int>> ps,is;
	vector<int> tmp;
	tmp.push_back(0);
	tmp.push_back(post.size()-1);
	ps.push(tmp);
	is.push(tmp);
	while(level.size()!=post.size()){
		vector<int> p,i;
		p=ps.front();ps.pop();
		i=is.front();is.pop();
		level.push_back(post[p[1]]);
		int r=i[0];
		while(in[r]!=post[p[1]])r++;
		tmp.clear();
		if(i[0]!=r){
			tmp.push_back(p[0]);
			tmp.push_back(p[0]+r-i[0]-1);
			ps.push(tmp);
			tmp.clear();
			tmp.push_back(i[0]);
			tmp.push_back(r-1);
			is.push(tmp);
			tmp.clear();
		}
		if((r)<i[1]){
			tmp.push_back(p[0]+r-i[0]);
			tmp.push_back(p[1]-1);
			ps.push(tmp);
			tmp.clear();
			tmp.push_back(r+1);
			tmp.push_back(i[1]);
			is.push(tmp);
			tmp.clear();
		}
	}
}

int main(){
	int n;
	cin>>n;
    if (n==0)return 0;
	vector<int> postorder(n,0),inorder(n,0);
	for(int i=0;i<n;i++)
		cin>>postorder[i];
	for(int i=0;i<n;i++)
		cin>>inorder[i];
	tolevel(postorder,inorder);
    int i=0;
	for(i=0;i<n-1;i++)cout<<level[i]<<" ";
	cout<<level[i];
	return 0;
}

你可能感兴趣的:(PAT甲级刷题历程)