PAT甲级1086题 Tree Traversals Again,类似的是1020题 Tree Traversals,只不过1020题意更直白(直接告知后序和中序遍历序列,求前序遍历序列)。
1086. Tree Traversals Again (25)
时间限制200 ms
内存限制65536 kB
代码长度限制16000 B
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.
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
1086题目是给出用栈的形式中序访问一颗二叉树的顺序,然后求后序遍历序列。Push的顺序实际上就是前序遍历顺序(根左右),Pop出来的顺序就是中序遍历顺序(左根右),那么题目就转化为已知前序和中序,求后序序列的问题。
在这里借鉴柳婼大佬的代码,很是简洁。
void solve(int root,int start,int end){
if(start>end) return;//递归出口
int i=start;//i用来标记当前子树的根节点中序序列(in)中的下标
while(i<end&&in[i]!=pre[root]) i++;//root为当前子树根节点在前序序列(pre)中的下标
solve(root+1,start,i-1);
solve(root+1+i-start,i+1,end);
post.push_back(pre[root]);
}
solve(root+1,start,i-1); solve(root+1+i-start,i+1,end); 结合图片就能简单看出这两行的意思,先后对左右子树进行递归,最后post数组中存放的便是后序遍历序列。