PAT 1086. Tree Traversals Again

Posted A-Little-Nut

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT 1086. Tree Traversals Again相关的知识,希望对你有一定的参考价值。

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

分析

这道题是由树的前序遍历和中序遍历来获得树的后序遍历的意思,首先由输入的数据的按输入顺序储存到数组中获得先序遍历的顺序,然后按输入的操作,即每次遇到pop就pop出的元素储存在一个数组里获得中序遍历的结果。接下来就是由这两个部分获得后序遍历了,首先先序遍历的第一个元素一定是该子树的根节点,然后在中序遍历的数组中找到该数,由中序遍历的性质可知,该数左边的是根节点的左子树元素,右边的是右子树的元素,接下来就是对左右两边递归调用前面的部分了,不过要先调用右子树部分,因为最后输出是倒着输出的。

#include<iostream>
#include<vector>
#include<stack>
#include<algorithm>
using namespace std;
vector<int> preorder,inorder,postorder;
void getpost(int root,int s,int e){
    if(s>e) return ;
    postorder.push_back(preorder[root]);
    int index=find(inorder.begin(),inorder.end(),preorder[root])-inorder.begin();
    getpost(root+index-s+1,index+1,e);
    getpost(root+1,s,index-1);
}
int main(){
    int n,t;
    string order;
    cin>>n;
    stack<int> s;
    for(int i=0;i<2*n;i++){
        cin>>order;
        if(order=="Push"){
           cin>>t;
           preorder.push_back(t);
           s.push(t);
        }else{
            int u=s.top();
            s.pop();
            inorder.push_back(u);
        }
    }
    getpost(0,0,n-1);
    for(int i=n-1;i>=0;i--)
        i==n-1?cout<<postorder[i]:cout<<" "<<postorder[i];
    return 0;
} 

以上是关于PAT 1086. Tree Traversals Again的主要内容,如果未能解决你的问题,请参考以下文章

PAT 1086. Tree Traversals Again

PAT 甲级 1086 Tree Traversals Again

PAT 1086 Tree Traversals Again (25)

PAT Advanced 1086 Tree Traversals Again (25分)

1086. Tree Traversals Again (25)二叉树——PAT (Advanced Level) Practise

PAT Advanced 1086 Tree Traversals Again (25) [树的遍历]