輸入先序遍歷 ABCDE 和中序遍歷 BADCE,輸出後序遍歷 BDECA 並在控制台以樹形圖顯示:
A
|_B
|_C
|_D
|_E
│ ─ ├ └)。struct Node { char data; Node *left, *right; int row, col; };
Node* rebuild(string pre, string in) {
if (pre.empty()) return nullptr;
Node* root = new Node{pre[0], nullptr, nullptr, 0, 0};
size_t pos = in.find(pre[0]);
root->left = rebuild(pre.substr(1, pos), in.substr(0, pos));
root->right = rebuild(pre.substr(pos+1), in.substr(pos+1));
return root;
}
void postorder(Node* r) {
if (!r) return;
postorder(r->left);
postorder(r->right);
cout << r->data;
}
// 打印邏輯參考原帖完整代碼,核心是計算 row/col 並填充字符矩陣