思路是先构造出树,然后在后序遍历整个树。
#include<iostream>
#include<string>
using namespace std;
struct Tnode{
char data;
struct Tnode* left;
struct Tnode* right;
};
typedef struct Tnode Tree;
Tree* build(string pre,int h1,int t1,string in,int h2,int t2){
if(h1>t1) return NULL;
Tree* root =new Tree;
root->data=pre[h1];
root->left=NULL;
root->right=NULL;
if(h1==t1) return root;
int i=h2;
for(;i<=t2;i++){
if(in[i]==pre[h1]) break;
}
root->left=build(pre,h1+1,h1+i-h2,in,h2,i-1);
root->right=build(pre,h1+i-h2+1,t1,in,i+1,t2);
return root;
}
void postorder(Tree* root){
if(!root) return;
postorder(root->left);
postorder(root->right);
cout << root->data ;
}
int main(){
string preorder,inorder;
while(cin >> preorder >>inorder){
Tree* root=build(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
postorder(root);
cout << '\n';
}
return 0;
}
结果:
标签:pre,int,KY212,h1,Tree,C++,h2,二叉树,root From: https://www.cnblogs.com/llllmz/p/17985746