# 【华为练习题】二叉树遍历

ABC
BAC
FDXEAG
XDEFAG

BCA
XEDGAF

## 解答

#include <iostream>
#include <string>
using namespace std;

struct BTreeNode
{
char value;
BTreeNode *left;
BTreeNode *right;
};

void findBack(const string &front, const string &mid, BTreeNode *root){
char value = front[0];
int index = mid.find(value), length = (int)front.size();
if (index < 0) return;
if (index > 0)
{
char leftValue = front[1];
BTreeNode *left = new BTreeNode;
root->left = left;
left->value = leftValue;
left->left = NULL;
left->right = NULL;
findBack(string(front.begin()+1, front.begin()+index+1), string(mid.begin(), mid.begin()+index),left);
}
if (index < length - 1)
{
char rightValue = mid[index + 1];
BTreeNode *right = new BTreeNode;
root->right = right;
right->value = rightValue;
right->left = NULL;
right->right = NULL;
findBack(string(front.begin()+index+1, front.end()), string(mid.begin()+index+1,mid.end()),right);
}
}

void backVisit(BTreeNode *root){
if (root->left) backVisit(root->left);
if (root->right) backVisit(root->right);
cout << root->value;
delete root;
}

int main(){
string front, mid;
while (cin >> front >> mid)
{
BTreeNode *root = new BTreeNode;
root->value = front[0];
findBack(front, mid, root);
backVisit(root);
cout << endl;
}
return 0;
}