# 03-树3 Tree Traversals Again

#### 03-树3 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.

Figure 1

### Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer  () which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to ). Then  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

Pre    1    2    3    4    5    6

In      3    2    4    1    6    5

Post  3    4    2    6    5    1

#include <iostream>
#include <string>
using namespace std;

int pre[31], in[31], post[31], tempPre[31];		// 建立前序、中续、后续、存放前序遍历结果的数组

void solve(int preL, int inL, int postL, int n)        // 前序、中序、后序数组下标和结点个数
{
if (n == 0)        // 如果没有结点，这种情况在在左右子树缺少时出现
return;
if (n == 1)        // 如果只剩一个结点
{
post[postL] = pre[preL];
return;
}
int root = pre[preL], i;
post[postL + n - 1] = root;		// 把根节点放入后续数组的尾巴上
for (i = 0; i < n; i++)
{
if (in[inL + i] == root)
break;
}
int L = i;			// 左分支的结点数
int R = n - L - 1;	// 右分支的结点数，这里还要再减1是把中序遍历的根结点去掉
solve(preL+1, inL, postL, L);	// 递归调用左分支
solve(preL+L+1, inL+L+1, postL+L, R); // 递归调用右分支
}

int main(int argc, char const *argv[])
{
int N, x, idxPop = 0, idxPre = 0, tempIdxPre = 0;
string operation;				// 表示操作
cin >> N;
while (idxPop < N)				// 当Pop操作达到N次说明以结束
{
cin >> operation;
if (operation == "Push")
{
cin >> x;
pre[idxPre++] = x;
tempPre[tempIdxPre++] = x;
}
else{
in[idxPop++] = tempPre[--tempIdxPre];	//	把tempPre数组的"栈顶"弹出放入in
}
}
solve(0, 0, 0, N);
for (int i = 0; i < N; i++)		// 输出格式
{
if (i != 0)
cout << " ";
cout << post[i];
}
return 0;
}