1086 Tree Traversals Again

本文介绍了一种使用前序和中序遍历构建二叉树的方法,并实现了后序遍历输出。通过递归算法,文章详细解释了如何根据前序和中序遍历序列构建二叉树结构,然后进行后序遍历打印节点值。
#include<bits/stdc++.h>
using namespace std;
struct Node{
	int value;
	Node* left;
	Node* right;
};
vector<int> pre,in,pos,qu;
Node* build(int prel,int prer,int inl,int inr){
	if(prel>prer) return 0;
	Node* root=new Node;
	root->value=pre[prel];
	root->left=NULL;
	root->right=NULL;
	int k;
	for(k=inl;k<=inr;k++){
		if(pre[prel]==in[k]){
			break;
		}
	}
	int numleft=k-inl;
	root->left=build(prel+1,prel+numleft,inl,k-1);
	root->right=build(prel+numleft+1,prer,k+1,inr);
	return root;
}
void postra(Node* root){
	if(root==NULL) return;
	postra(root->left);
	postra(root->right);
	pos.push_back(root->value);
}
int main(){
	#ifndef ONLINE_JUDGE
	freopen("in.txt","r",stdin);
	#endif
	int n;
	cin>>n;
	for(int i=0;i<n*2;i++){
		string temp;
		int t;
		cin>>temp;
		if(temp=="Push"){
			cin>>t;
			pre.push_back(t);
			qu.push_back(t);
		}else if(temp=="Pop"){
			in.push_back(qu[qu.size()-1]);
			qu.erase(qu.begin()+qu.size()-1);
		}
	}
	Node* root=build(0,n-1,0,n-1);
	postra(root);
	for(int i=0;i<n;i++){
		if(i==0) cout<<pos[i];
		else cout<<' '<<pos[i];
	}
	cout<<endl;
	return 0;
}

玄学垃圾!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值