#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
struct TreeNode{
int data;
TreeNode *leftchild;
TreeNode *rightchild;
};
TreeNode* Build(string str1,string str2){
if(str1.size() == 0) return NULL;
char c = str1[0];
TreeNode* root = new TreeNode();
root->data = c;
root -> leftchild = NULL;
root -> rightchild = NULL;
int position = str2.find(c);//string的find()找到坐标
root->leftchild = Build(str1.substr(1,position),str2.substr(0,position));//前序position个对应中序前position个
root->rightchild = Build(str1.substr(position + 1),str2.substr(position + 1));
return root;
}
void PostOrder(TreeNode* root){
if(root == NULL) return;
PostOrder(root->leftchild);
PostOrder(root->rightchild);
printf("%c",root->data);
return;
}
int main(){
string str;
while(cin>>str){
string str2;
cin>>str2;
TreeNode* root = Build(str,str2);
PostOrder(root);
printf("\n");
}
return 0;
}
根据前序中序生成树
最新推荐文章于 2022-06-24 10:57:13 发布