HDU1710 Binary Tree Traversals 题解 树的遍历
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1710
题目大意:
告诉你一棵二叉树的先序遍历、中序遍历,求后序遍历。
解题思路:
递归求解。
实现代码如下:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1010;
int a[maxn], b[maxn], n;
vector<int> c;
void handle(int L1, int R1, int L2, int R2) {
int i;
for (i = L2; a[L1] != b[i]; i ++);
int len1 = i - L2, len2 = R2 - i;
if (len1) handle(L1+1, L1+len1, L2, i-1);
if (len2) handle(R1-len2+1, R1, i+1, R2);
c.push_back(a[L1]);
}
int main() {
while (cin >> n) {
for (int i = 0; i < n; i ++) cin >> a[i];
for (int i = 0; i < n; i ++) cin >> b[i];
c.clear();
handle(0, n-1, 0, n-1);
for (int i = 0; i < n; i ++) {
if (i) cout << " ";
cout << c[i];
}
cout << endl;
}
return 0;
}