代码如下:
#include <iostream>
using namespace std;
const int N = 1010;
int in_order[N], post_order[N], lch[N], rch[N];int build(int inL, int inR, int postL, int postR) {if (inL > inR)return 0;int root = post_order[postR];int k = inL;while (in_order[k] != root)k++;int numLeft = k - inL;lch[root] = build(inL, k - 1, postL, postL + numLeft - 1);rch[root] = build(k + 1, inR, postL + numLeft, postR - 1);return root;
}void dfs(int u) {cout << u << " ";if (lch[u])dfs(lch[u]);if (rch[u])dfs(rch[u]);
}int main() {int n;cin >> n;for (int i = 0; i < n; i++)cin >> in_order[i];for (int i = 0; i < n; i++)cin >> post_order[i];build(0, n - 1, 0, n - 1);dfs(post_order[n - 1]);return 0;
}
测试结果: