1086. Tree Traversals Again (25)
An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.
![](http://nos.patest.cn/bs_n9mde9jcnyj.jpg)
Figure 1
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (<=30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: "Push X" where X is the index of the node being pushed onto the stack; or "Pop" meaning to pop one node from the stack.
Output Specification:
For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:6 Push 1 Push 2 Push 3 Pop Pop Push 4 Pop Pop Push 5 Push 6 Pop PopSample Output:
3 4 2 6 5 1
题意:
入栈顺序是前序遍历序列
出栈顺序是中序遍历序列
求后续遍历
思路:
搞懂了题意即可。另外写build递归时,参数切忌不要搞错
不要去思考简单解法,这个熟悉的思路将是最简单的。
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<stack>
#include<vector>
#include<queue>
#include<string>
#include<map>
using namespace std;
#define INF 99999999
#define M 300
//start 23:07
//end 23:40
vector<int> PREV,midv,postv;
int lc[M],rc[M];
int build(int prel,int prer,int midl,int midr)
{
int i;
if(prel>prer||midl>midr)
return -1;
int root=PREV[prel];
for(i=midl;i<=midr;i++)
if(midv[i]==root)
break;
lc[root]=build(prel+1,prel+1+i-1-midl,midl,i-1);
rc[root]=build(prel+1+i-midl,prer,i+1,midr);
return root;
}
void rebuild()
{
build(0,PREV.size()-1,0,midv.size()-1);
}
void printpost(int root)
{
if(root==-1)
return ;
printpost(lc[root]);
printpost(rc[root]);
postv.push_back(root);
}
int main(){
int n;
string cmds;
stack<int> s;
cin>>n;
int nodenum,i;
for(i=0;i<2*n;i++)
{
cin>>cmds;
if(cmds[1]=='u')
{
scanf("%d",&nodenum);
s.push(nodenum);
PREV.push_back(nodenum);
}
else
{
nodenum=s.top();
midv.push_back(nodenum);
s.pop();
}
}
rebuild();
printpost(PREV[0]);
for(i=0;i<postv.size();i++)
{
printf("%d",postv[i]);
if(i!=postv.size()-1)
printf(" ");
else cout<<endl;
}
}