pat-1086. Tree Traversals Again 树的构建

来源:互联网 发布:淘宝香云纱 编辑:程序博客网 时间:2024/06/06 06:35


1086. Tree Traversals Again (25)

时间限制
200 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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.


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:
6Push 1Push 2Push 3PopPopPush 4PopPopPush 5Push 6PopPop
Sample 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:40vector<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;}}