PAT.A1086 Tree Traversals Again

返回目录

在这里插入图片描述

题意

用栈模拟一颗二叉树的先序序列和中序序列,求该二叉树的后序遍历序列。

样例(可复制)

6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
//output
3 4 2 6 5 1

注意点

  1. 本题模拟出的先序序列为:1 2 3 4 5 6
  2. 本题模拟出的先序序列为:3 2 4 1 6 5
  3. 本题与上题类似,增加了一个模拟过程,其中push进的数字序列是先序序列,pop出的数字序列是中序序列
  4. 建议读者模拟一遍create函数
  5. 输出先、中、后续遍历的方式采用递归较方便,其格式也很固定,可以记下来
#include<bits/stdc++.h>
using namespace std;

const int maxn=30; 
int pre[maxn],in[maxn],post[maxn],n,num=0;
struct node{
	int data;
	node* lc;
	node* rc;
};
node* create(int prel,int prer,int inl,int inr){
	if(prel>prer)return NULL;
	node* root=new node;
	root->data=pre[prel];
	int k;
	for(k=inl;k<inr;k++){
		if(in[k]==pre[prel])break;
	}
	int numleft=k-inl;
	root->lc=create(prel+1,prel+numleft,inl,k-1);
	root->rc=create(prel+numleft+1,prer,k+1,inr);
	return root;
}
void postorder(node* root){
	if(root==NULL)return;
	postorder(root->lc);
	postorder(root->rc);
	printf("%d",root->data);
	num++;
	if(num<n)printf(" ");
}
int main(){
	int tmp,preindex=0,inindex=0;
	char a[5];
	stack<int> st;
	cin>>n;
	for(int i=0;i<2*n;i++){
		scanf("%s",a);
		if(strcmp(a,"Push")==0){
			scanf("%d",&tmp);
			pre[preindex++]=tmp;
			st.push(tmp);
		}else{
			in[inindex++]=st.top();
			st.pop();
		}
	}
	node* root=create(0,n-1,0,n-1);
	postorder(root);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小怪兽会微笑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值