题目链接
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:
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
Sample Output:
3 4 2 6 5 1
思路:按照栈的方式建立二叉树,RT,发现入栈的序列时前序序列,出栈的序列是中序序列,那么输出的是后序序列。 建立二叉树输出即可。
代码;
#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for(int i=a;i<n;i++)
#define drep(i,n,a) for(int i=n;i>=a;i--)
#define mem(a,n) memset(a,n,sizeof(a))
#define lowbit(i) ((i)&(-i))
typedef long long ll;
typedef unsigned long long ull;
const ll INF=0x3f3f3f3f;
const double eps = 1e-6;
const int N = 1e5+5;
vector<int>in,pre;
stack<int>st;
int n;
int findRoot(int pos) {
for(int i=0; i<n; i++) {
if(in[i]==pre[pos]) {
return i;
}
}
}
void inOrder(int L,int R,int pos) {
if(L>R) return;
int rootPos=findRoot(pos);
inOrder(L,rootPos-1,pos+1);
inOrder(rootPos+1,R,pos+rootPos-L+1);
if(pos) cout<<pre[pos]<<" ";
else cout<<pre[pos]<<endl;
}
int main() {
string str;
cin>>n;
for(int i=0; i<n*2; i++) {
cin>>str;
if(str[1]=='u') {
int node;
cin>>node;
st.push(node);
pre.push_back(node);
} else {
in.push_back(st.top());
st.pop();
}
}
// cout<<in[0]<<" "<<pre[0]<<endl;
inOrder(0,n-1,0);
return 0;
}