文章
121
粉丝
68
获赞
94
访问
20.3k
#include <bits/stdc++.h>
using namespace std;
struct tnode{
char val;
struct tnode* left,* right;
tnode(char val):val(val),left(nullptr),right(nullptr){}
};
tnode* buildTree(string inOrder,string postOrder){
if(postOrder.empty())return nullptr;
char rootval=postOrder[postOrder.size()-1];
int inPos=inOrder.find(rootval);
tnode* root=new tnode(rootval);
root->left=buildTree(inOrder.substr(0,inPos),postOrder.substr(0,inPos));
root->right=buildTree(inOrder.substr(inPos+1),postOrder.substr(inPos,postOrder.size()-1-inPos));
root->val=rootval;
return root;
}
void preOrder(tnode *root){
if(root==nullptr)return;
cout<<root->val;
preOrder(root->left);
preOrder(root->right);
}
int main(){
string in,post;
while(cin>>in>>post){
preOrder(buildTree(in,post));
}
}
思路基本上和先序中序创建是一样的,主要是这里会使用后续字符串,就使用后续输出,中序依然是辅助字符串,确认左右子树的长度用
登录后发布评论
暂无评论,来抢沙发