PAT 1127 ZigZagging on a Tree

PAT 1127 ZigZagging on a Tree
PAT 1127 ZigZagging on a Tree
题解:
PAT 1127 ZigZagging on a Tree

代码:

#include<iostream>
#include<vector>
using namespace std;
const int maxv=39;
vector<int> tree[maxv];
int in[maxv],post[maxv];
int layer=1;
void layertravel(int postL,int postR,int inL,int inR,int nowlayer){
	if(layer<nowlayer) layer=nowlayer;
	if(postL>=postR) return;
	int k=inL;
	while(in[k]!=post[postR]) k++;
	int numL=k-inL;
	if(numL!=0){
	tree[nowlayer+1].push_back(post[postL+numL-1]); //左子节点
//	cout<<nowlayer+1<<": "<<post[postL+numL-1]<<endl;
	layertravel(postL,postL+numL-1,inL,k-1,nowlayer+1);//层序遍历左子树
    }
    if(postL+numL!=postR){
    	tree[nowlayer+1].push_back(post[postR-1]); //右子节点
    //	cout<<nowlayer+1<<": "<<post[postR-1]<<endl;
    	layertravel(postL+numL,postR-1,k+1,inR,nowlayer+1);//层序遍历左子树
	}
	 
}
int main(){
	int n;
	cin>>n;
	for(int i=1;i<=n;i++) cin>>in[i];
	for(int i=1;i<=n;i++) cin>>post[i];
	tree[1].push_back(post[n]);
	layertravel(1,n,1,n,1);
	for(int i=1;i<layer;i++){
		if(i%2==0){
			for(int j=0;j<tree[i].size();j++)
			cout<<tree[i][j]<<" ";
			
		}
		else{
			for(int j=tree[i].size()-1;j>=0;j--)
			cout<<tree[i][j]<<" ";
		}
	}
	//cout<<endl;
//	cout<<tree[layer].size()<<endl;
	if(layer%2==0){
		for(int i=0;i<tree[layer].size();i++) printf("%d%s",tree[layer][i],i==tree[layer].size()-1?"\n":" ");
	}
	else{
		for(int i=tree[layer].size()-1;i>=0;i--) printf("%d%s",tree[layer][i],i==0?"\n":" ");
	}
	return 0;
}

在第一次构建代码之前一定要想清楚再想清楚,不然会因为小错误及一些漏掉的地方浪费巨多时间。

上一篇:grok debugger 正则解析nginx日志


下一篇:根据中序、后续遍历序列构建二叉树