PAT-A1086 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.

PAT-A1086 Tree Traversals Again 题目内容及题解

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

题目大意

有数据结构知道可以使用堆栈以非递归的方式实现二叉树中序遍历。题目给出一个栈的操作序列,其可以生成一个惟一的二叉树。题目要求是给出此二叉树的后序遍历序列。

解题思路

  1. 读取题目所给的栈操作序列,分别获取其入栈顺序和出栈顺序;
  2. 其入栈序列为前序遍历,出栈顺序为中序遍历;
  3. 由前序遍历和中序遍历生成二叉树;
  4. 后序遍历该二叉树;
  5. 输出结果并返回零值。

代码

#include<cstdio>
#include<vector>
using namespace std;

vector<int> pre,in,post;

struct Node{
    int data;
    Node *lchild,*rchild;
};

Node* NewNode(int v){
    Node *root=new(Node);
    root->data=v;
    root->lchild=NULL;
    root->rchild=NULL;
    return root;
}

Node* Create(int PreL,int PreR,int InL,int InR){
    int k,numleft=0;
    if(PreL>PreR){
        return NULL;
    }
    Node* root=NewNode(pre[PreL]);
    for(k=InL;k<InR;k++){
        if(in[k]==pre[PreL]){
            break;
        }
        numleft++;
    }
    root->lchild=Create(PreL+1,PreL+numleft,InL,k-1);
    root->rchild=Create(PreL+numleft+1,PreR,k+1,InR);
    return root; 
}

void PostOrder(Node* root){
    if(root==NULL){
        return;
    }
    PostOrder(root->lchild);
    PostOrder(root->rchild);
    post.push_back(root->data);
}

int main(){
    int N;
    int i,a;
    char s[6];
    int stack[35],top=0;
    scanf("%d",&N);
    while(in.size()<N){
        scanf("%s",&s);
        if(s[1]=='u'){
            scanf("%d",&a);
            pre.push_back(a);
            stack[top++]=a;
        }else{
            in.push_back(stack[--top]);
        }
    }
    Node* root=Create(0,N-1,0,N-1);
    PostOrder(root);
    for(i=0;i<N;i++){
        printf("%d",post[i]);
        if(i<N-1){
            printf(" ");
        }else{
            printf("\n");
        }
    }
    return 0;
}

运行结果

PAT-A1086 Tree Traversals Again 题目内容及题解