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 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

题解:

#include <iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<cstring>
#define mod 1000000007
const int INF = 0x3f3f3f3f;
typedef long long ll;
using namespace std;
int a[50], b[50];
int c[50];
struct node
{
    bool data;
    int lc;
    int rc;
};
node tree[35];
int t;
void solve(int prel, int inl, int postl, int n)
{
    if(n==0) return;
    if(n==1) {c[postl]=a[prel];return;}
    int root = a[prel];
    c[postl+n-1] = root;
    int i;
    for(i = 0; i < n; i++)
        if(b[inl+i] == root)
            break;
    int l = i, r = n - l - 1;
    solve(prel+1, inl, postl, l);
    solve(prel+l+1, inl+l+1, postl+l, r);
}
int main()
{

    scanf("%d", &t);
    stack<int> sta;
    char temp[10];
    int q = 0, d = 0;
    for(int i = 0; i < 2*t; i++)
    {
        scanf("%s", temp);
        if (!strcmp(temp, "Push")){
            scanf("%d", &a[q]);
            sta.push(a[q]);
            q++;
        }
        else{
            b[d++] = sta.top();
            sta.pop();
        }
    }
    solve(0,0,0,t);
    for(int i = 0; i < t; i++)
        if(i == 0)
        printf("%d",c[i]);
        else
        printf(" %d",c[i]);
    return 0;
}

posted @ 2018-05-04 14:02  focus5679  阅读(115)  评论(0编辑  收藏  举报