此题主要考察二叉树,根据给出先序遍历和中序遍历求后序遍历。
代码如下:
#include <iostream> #include <string> //#include <fstream> using namespace std; class Node{ public: Node *left, *right; char data; }; //AEFDHZMG //build tree void build(string preord, string inord, Node *root) { root->data = preord[0]; if(preord.length() == 1) { return ; } int rootLoc = inord.find(preord[0]); int rightLoc = preord.find(inord[rootLoc+1]); //cout << rightLoc << endl; //建立左子树 if(rootLoc > 0) { root->left = new Node(); build(preord.substr(1, rootLoc), inord.substr(0, rootLoc), root->left); } //建立右子树 if(rightLoc > 0) { root->right = new Node(); build(preord.substr(rootLoc + 1), inord.substr(rootLoc+1), root->right); } } //后序遍历二叉树 void postorder(Node *root) { if(root->left) { postorder(root->left); } if(root->right) { postorder(root->right); } cout << root->data; } int main() { //ifstream in("data2255.in"); string preord, inord, postord; while (cin >> preord >> inord) { Node *root = new Node(); build(preord, inord, root); postorder(root); cout << endl; delete root; } return 0; }