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;
}
发布了177 篇原创文章 · 获赞 5 · 访问量 6673

猜你喜欢

转载自blog.csdn.net/a1920993165/article/details/105475736
今日推荐