#include <iostream>
using namespace std;
struct TreeNode{
char data;
TreeNode*leftChild;
TreeNode*rightChild;
TreeNode(char c):data(c),leftChild(nullptr),rightChild(nullptr){}; //构造函数
};
TreeNode*Build(string preOrder,string inOrder){ //根据先序和中序序列建树
if(preOrder.size()==0) return nullptr; //递归终止
char c=preOrder[0];
TreeNode*root=new TreeNode(c);
int position=inOrder.find(c);
root->leftChild=Build(preOrder.substr(1,position),inOrder.substr(0,position)); //从1开始,长度是position
root->rightChild=Build(preOrder.substr(position+1),inOrder.substr(position+1)); //从position+1开始一直到结束
return root;
}
void PostOrder(TreeNode *root){ //后序遍历
if(root==nullptr) return;
PostOrder(root->leftChild);
PostOrder(root->rightChild);
printf("%c",root->data);
}
int main() {
string preOrder,inOrder;
while(cin>>preOrder>>inOrder){
TreeNode *root=Build(preOrder,inOrder);
PostOrder(root);
cout<<endl;
}
system("pause");
return 0;
}
前序、中序遍历转后序遍历
于 2022-02-26 10:16:26 首次发布