a756中等前序定根與中序分割子樹
CPE:Tree Recovery (UVa 536)
不用建節點物件也能直接產生後序。
解題思路
前序的第一個字母是目前子樹根,找到它在中序的位置後,左側恰好是左子樹、右側恰好是右子樹。由中序左段長度可知前序接下來幾個字母屬於左子樹,剩下屬於右子樹,分割因字母不重複而唯一。
使用區間索引和全域前序游標遞迴:取根、遞迴左區間、遞迴右區間、最後把根加入輸出。先建立字母到中序位置的表,每個根能 O(1) 定位。每行兩字串讀到 EOF,輸出後序字串,每筆一行;空子樹區間直接返回。
Step-by-step animation
示意:pre=BAC,in=ABC
步驟 1 / 3
根 B
B 在中序索引 1,左右分別是 A、C。
A
B
C
- pre游標
- 1
#include <iostream>
#include <string>
#include <functional>
using namespace std;
int main() {
string pre, in;
while (cin >> pre >> in) {
int pos[256] = {};
for (int i = 0; i < int(in.size()); ++i)
pos[(unsigned char)in[i]] = i;
int at = 0;
string out;
function<void(int, int)> visit = [&](int l, int r) {
if (l >= r)
return;
char root = pre[at++];
int m = pos[(unsigned char)root];
visit(l, m);
visit(m + 1, r);
out += root;
};
visit(0, in.size());
cout << out << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。