PAT(A) 1086

push的顺序即为先序遍历

pop的顺序为中序遍历

根据先序遍历和中序遍历求后序遍历

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stack>
#include<vector> 
using namespace std;
stack<int> s1;
void PreAndIn(int inorder[],int preorder[],int n){
	if(n == 0)
		return ;
	int root;
	root = preorder[0];
	int i;
	for(i = 0;i<n;i++)
		if(inorder[i] == root)
			break;
	s1.push(root);
	PreAndIn(inorder + i+1,preorder + i+1,n-i-1);//右子树先递归,先进stack实现postorder 
	PreAndIn(inorder,preorder+1,i);
}
int main(){
	int i,j,pp,ip;
	char str[10];
	int n,num;
	int preorder[35],inorder[35];
	//FILE *fp;
	//fp = fopen("1.in","r");
	fscanf(stdin,"%d",&n);
	stack<int> s;
	pp = ip = 0;
	int count = 0;
	while(count<n){
		fscanf(stdin,"%s",str);
		if(!strcmp(str,"Push")){
			fscanf(stdin,"%d",&num);
			preorder[pp++] = num;
			s.push(num);
		}
		else {
			num = s.top();
			s.pop();
			inorder[ip++] = num;
			count++;
		}
	}
	//for(i = 0;i<n;i++)
	//printf("%d ",preorder[i]);
	//printf("\n");
	//for(i = 0;i<n;i++)
	//printf("%d ",inorder[i]);
PreAndIn(inorder,preorder,n);
for(i = 0;i<n;i++){
	printf("%d",s1.top());
	s1.pop();
	if(i == n-1)
		printf("\n");
	else printf(" ");
}
return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值