返回顶部

POJ - 2255 - Tree Recovery = 二叉树遍历

http://poj.org/problem?id=2255

题意:给定先序遍历和中序遍历,求后序遍历。

回忆以前上DataStructure课的时候貌似写过类似的。

先从先序入手,从左到右扫描,进入时节点时立刻入栈,离开节点时立刻出栈。

关键是怎么知道什么时候才是立刻节点了呢?

貌似只有n^2的做法,因为要从中序遍历序列中找根。

但其实假如预处理出中序遍历的序列中的字母每个指向的位置就不用这额外的时间花费n了。

也就是从先序遍历入手,进入节点时把根节点的中序遍历序列指针两侧递归下去。

所以构造的形式如同一棵线段树。

#include<algorithm>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<map>
#include<set>
#include<stack>
#include<string>
#include<queue>
#include<vector>
using namespace std;
typedef long long ll;

char s[1005];
char t[1005];
int ss[1005];
int tt[1005];
char st[1005];
int top;

void build(int sl, int sr, int tl, int tr) {
    if(tl != tr) {
        int tm = tt[s[sl]];
        if(tm > tl) {
            //左子树还有
            build(sl + 1, sl + tm - tl, tl, tm - 1);
        }
        if(tm < tr) {
            //右子树还有
            build(sl + tm - tl + 1, sl + sr, tm + 1, tr);
        }
    }
    st[++top] = s[sl];
}

int main() {
#ifdef Yinku
    freopen("Yinku.in", "r", stdin);
#endif // Yinku
    while(~scanf("%s%s", s + 1, t + 1)) {
        top = 0;
        int n = strlen(s + 1);
        for(int i = 1; i <= n; ++i) {
            ss[s[i]] = i;
            tt[t[i]] = i;
        }
        build(1, n, 1, n);
        for(int i = 1; i <= n; ++i)
            printf("%c", st[i]);
        printf("\n");
    }
}

实现起来的细节还是蛮多的。但本质上是通过dfs序连续这个性质进行分治。

posted @ 2019-10-22 12:11  Inko  阅读(103)  评论(0编辑  收藏  举报