PAT A1086 Tree Traversals Again(25 分)---树的遍历--由进出栈情况确定树

总结:

1.读懂题意,比如这道题可以根据进栈情况确定前序遍历,由出栈确定中序遍历,后序遍历序列就好求了

2.入栈序列为前序遍历,出栈为中序遍历                

代码:

#include <iostream>
#include<stack>
#include<string>
using namespace std;
int pre[100];
int in[100];
stack<int>pp;
int cnt = 0;
int n = 0;
void pre1(int root, int start, int end) {
    if (start > end) return;
    int i = start;
    while (i < end && in[i] != pre[root]) i++;
    pre1(root+1, start, i - 1);
    pre1(root+1+i-start, i + 1, end);
    printf("%d", pre[root]); if (cnt != n - 1)printf(" ");
        cnt++;
    
}

int main()
{
    int g1 = 0,g2 = 0;
    cin >> n;
    for (int i = 0; i < 2*n; i++)
    {
        string a; int node;
        cin >> a;
        if (a == "Push"){ cin >> node; pp.push(node); pre[g1++] = node; }
        else if (a == "Pop"){ in[g2++] = pp.top(); pp.pop(); }
    }
    pre1(0,0,n-1);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/luoshiyong123/article/details/81946442
今日推荐