真二叉樹重構(Proper Rebuild)

<center>真二叉樹重構(Proper Rebuild)</center>


Description

In general, given the preorder traversal sequence and postorder traversal sequence of a binary tree, we cannot determine the binary tree.node

img

Figure 1post

In Figure 1 for example, although they are two different binary tree, their preorder traversal sequence and postorder traversal sequence are both of the same.ui

But for one proper binary tree, in which each internal node has two sons, we can uniquely determine it through its given preorder traversal sequence and postorder traversal sequence.spa

Label n nodes in one binary tree using the integers in [1, n], we would like to output the inorder traversal sequence of a binary tree through its preorder and postorder traversal sequence.code

Input

The 1st line is an integer n, i.e., the number of nodes in one given binary tree,blog

The 2nd and 3rd lines are the given preorder and postorder traversal sequence respectively.遞歸

Output

The inorder traversal sequence of the given binary tree in one line.ip

Example

Inputinput

5
1 2 4 5 3
4 5 2 3 1

Outputit

4 2 5 1 3

Restrictions

For 95% of the estimation, 1 <= n <= 1,000,00

For 100% of the estimation, 1 <= n <= 4,000,000

The input sequence is a permutation of {1,2...n}, corresponding to a legal binary tree.

Time: 2 sec

Memory: 256 MB

Hints

img

Figure 2

In Figure 2, observe the positions of the left and right children in preorder and postorder traversal sequence.

  1. **原理與要點:**利用樹的先序與後序的規律,遞歸建樹,而後dfs輸出樹的中序遍歷。能夠發現先序的第一個節點是根節點,後序的最後一個節點是根節點,利用這個規律肯定左右子樹,一直遞歸下去,就能夠肯定每個節點
  2. **遇到的問題:**無
  3. **時間和空間複雜度:**時間複雜度$O(nlogn)$,空間複雜度$O(n)$
#include <cstdlib>
#include "cstdio"

using namespace std;
const int maxn = 4e6 + 100;
const int SZ = 1 << 20;  //快速io
struct fastio {
    char inbuf[SZ];
    char outbuf[SZ];

    fastio() {
        setvbuf(stdin, inbuf, _IOFBF, SZ);
        setvbuf(stdout, outbuf, _IOFBF, SZ);
    }
} io;

typedef struct node {
    int val;
    node *l, *r;
} *tree;
tree root = NULL;

int mlr[maxn], lrm[maxn];
int n;

void build(tree &t, int s1, int e1, int s2, int e2) {

    t = (tree) malloc(sizeof(node));
    t->val = mlr[s1];
    if (s1 == e1) return;
    int now;
    for (int i = s2; i <= e2; i++) {
        if (mlr[s1 + 1] == lrm[i]) {
            now = i;
            break;
        }
    }
    build(t->l, s1 + 1, now - s2 + 1 + s1, s2, now);
    build(t->r, now - s2 + 2 + s1, e1, now + 1, e2 - 1);
}

void dfs(tree now) {
    if (now == NULL) return;
    dfs(now->l);
    printf("%d ", now->val);
    dfs(now->r);
}

int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        scanf("%d", &mlr[i]);
    }
    for (int i = 1; i <= n; i++) {
        scanf("%d", &lrm[i]);
    }
    build(root, 1, n, 1, n);
    dfs(root);
    return 0;
}
相關文章
相關標籤/搜索