分治思想,递归求解。
先建树再后序遍历:
#include <iostream> #include <algorithm> #include <cstring> using namespace std; char pre[26], mid[26]; typedef struct _tree { char c; _tree *lc, *rc; _tree(char ch) { c = ch; } } Tree, *PTree; PTree makeTree(int pb, int mb, int len) { if (len <= 0) return nullptr; char root_char = pre[pb]; int idx; for (idx = mb; idx < mb + len; idx++) { if (mid[idx] == root_char) { break; } } PTree root = new Tree(root_char); root->lc = makeTree(pb + 1, mb, idx - mb); root->rc = makeTree(pb + 1 + idx - mb, idx + 1, mb + len - idx - 1); return root; } void post_traverse(PTree root) { if (root == nullptr) return; post_traverse(root->lc); post_traverse(root->rc); cout << root->c; } int main() { cin >> pre >> mid; int len = strlen(pre); PTree root = makeTree(0, 0, len); post_traverse(root); return 0; }
实际上建树过程是可以略去的,处理时直接输出后序遍历结果:
#include <iostream> #include <algorithm> #include <cstring> using namespace std; char pre[26], mid[26]; void solve(int pb, int mb, int len) { if (len <= 0) return; char root_char = pre[pb]; int idx; for (idx = mb; idx < mb + len; idx++) { if (mid[idx] == root_char) { break; } } solve(pb + 1, mb, idx - mb); solve(pb + 1 + idx - mb, idx + 1, mb + len - idx - 1); cout << root_char; } int main() { cin >> pre >> mid; int len = strlen(pre); solve(0, 0, len); return 0; }
时间: 2024-10-12 07:30:56