对于二叉树,中序加其它任何一个序列(前序、后序、层序)即可重建二叉树,其它序列组合则不能重建。

下面以中序和后序为例

输入

第一行为一个整数n。

第二、三行,即已知的中序、后序遍历序列。

输出

若所给的中序、后序遍历序列的确对应于某棵二叉树,则输出其先序遍历序列。否则,输出-1。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
using namespace std;


bool flag = false;
int *inmap;

struct Node {
    int data;
    struct Node *left, *right;

    Node(int elem): data(elem), left(NULL), right(NULL) { }
};

void rebuildInPost(Node **p, int *in, int beginI, int endI, int *post, int beginP, int endP)
{
    if (!flag) {
        if(beginI > endI || beginP > endP)
            return;

        int elem = post[endP];
        int i;
        i = inmap[elem] - 1;
        if (i > endI) {
            flag = true;
            return;
        }
        int leftNum = i - beginI;
        *p = new Node(elem);
        rebuildInPost(&((*p)->left), in, beginI, i-1, post, beginP, beginP+leftNum-1);
        rebuildInPost(&((*p)->right), in, i+1, endI, post, beginP+leftNum, endP-1);
    }
}


void preOrder(Node *root)
{
    if (root != NULL) {
        cout << root->data << " ";
        preOrder(root->left);
        preOrder(root->right);
    }
}


void freeTree(Node *root)
{
    if (root == NULL)
        return;

    freeTree(root->left);
    freeTree(root->right);

    delete root;
}


int main()
{
    int num;
    cin >> num;
    int *in = new int[num];
    int *post = new int[num];
    inmap = new int[num + 1];

    int i;
    for (i = 0; i < num; i++)
        cin >> in[i];
    for (i = 0; i < num; i++)
        cin >> post[i];
    for (i = 1; i <= num; i++)
        inmap[in[i - 1]] = i;

    Node *root = NULL;
    rebuildInPost(&root, in, 0, num - 1, post, 0, num - 1);
    if (flag)
        cout << "-1";
    else
        preOrder(root);

    freeTree(root);
    delete []in;
    delete []post;
    delete []inmap;
}