【题目描述】
输入一棵二叉树的先序和中序遍历序列,输出其后序遍历序列。
【输入】
共两行,第一行一个字符串,表示树的先序遍历,第二行一个字符串,表示树的中序遍历。树的结点一律用小写字母表示。
【输出】
一行,表示树的后序遍历序列。
【输入样例】
abdec dbeac
【输出样例】
debca
#include <bits/stdc++.h> using namespace std; struct Node { char value; Node *left, *right; }; Node *CreateTree(const string &pre, const string &in) { if (pre.size() <= 0) { return nullptr; } else { // cout << pre << "," << in << endl; Node *root = new Node; root->value = pre[0]; int pos = in.find(pre[0]); string pre1 = pre.substr(1, pos); string in1 = in.substr(0, pos); root->left = CreateTree(pre1, in1); string pre2 = pre.substr(pos + 1); string in2 = in.substr(pos + 1); root->right = CreateTree(pre2, in2); return root; } } string PreOrder(Node *root) { string s; if (root != nullptr) { s.push_back(root->value); s += PreOrder(root->left); s += PreOrder(root->right); } return s; } string InOrder(Node *root) { string s; if (root != nullptr) { s += InOrder(root->left); s.push_back(root->value); s += InOrder(root->right); } return s; } string PostOrder(Node *root) { string s; if (root != nullptr) { s += PostOrder(root->left); s += PostOrder(root->right); s.push_back(root->value); } return s; } int main() { // freopen("1.txt", "r", stdin); string pre, in, post; cin >> pre >> in; Node *root = CreateTree(pre, in); // cout << PreOrder(root) << endl; // cout << InOrder(root) << endl; cout << PostOrder(root) << endl; return 0; }