PAT(A) 1086
来源:互联网 发布:事情进度跟踪软件 编辑:程序博客网 时间:2024/05/21 03:24
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;}
0 0
- PAT(A) 1086
- PAT A A+B Format
- pat: 1016 A+B
- PAT [A] 1054
- Pat(A) 1002
- PAT(A) 1005
- PAT(A) 1006
- PAT(A) 1007
- PAT(A) 1008
- PAT(A) 1009
- PAT(A) 1011
- PAT(A) 1012
- PAT(A) 1015
- PAT(A) 1031
- PAT(A) 1035
- PAT(A) 1013
- PAT(A) 1019
- PAT(A) 1004
- hollister kids watch TV hinder safe driving behavior
- 毛泽东1956年评抗美援朝:帮朝鲜打这场仗错了
- 博客学习日记-2014/11/22
- 现有1,2……一直到n的无序数组,求排序算法,并且要求时间复杂度为O(n),空间复杂度为O(1),使用交换,而且只能交换两个数
- 完美解决mysql下utf-8的乱码问题
- PAT(A) 1086
- VMWare中CentOS静态设置IP
- 【转载】Linux下 编译C++ - 转向c++专栏 - CSDN博客
- Unity选择循环结构题
- C# 中的委托和事件--详解
- DS Bonus 2: QQ Account Management
- Android Sleep和Wait区别
- flex中SDK选择不合适引起的问题
- 数据打包成JSON格式及其解析