前序+中序得出二叉树,靠着回忆推出的板子
ti
#include<bits/stdc++.h>
using namespace std;
struct tree{
char c;
tree *left, *right;
tree(char x):c(x), left(NULL), right(NULL){};
};
string s1, s2;
int n, m;
int t;
int a[110];
tree* build(char x){
tree *root;
root->c = x;
root->left = NULL;
root->right = NULL;
}
tree* Build(int pre, int in, int len){ //分别表示前序序列开始的位置,中序序列开始的位置,长度
if(len == 1){
tree *root = new tree(s1[pre]);
return root;
}
tree *root = new tree(s1[pre]);
for(int i = 0; i < len; i ++ ){
if(s2[i + in] == s1[pre]){
if(i != 0) root->left = Build(pre + 1, in, i);
else root->left = NULL;
if(pre + i + 1 < pre + len) root->right = Build(pre + i + 1, in + i + 1, len - i - 1);
else root->right = NULL;
break;
}
}
return root;
}
void houxu(tree *root){
if(root == NULL) return ;
if(root->left != NULL) houxu(root->left);
if(root->right != NULL) houxu(root->right);
cout<<root->c;
return ;
}
int main()
{
while(cin>>s1>>s2){
tree *root = Build(0, 0, s1.length());
houxu(root);
cout<<endl;
}
return 0;
}