#include<iostream>
using namespace std;
struct treeNode
{
treeNode *leftchild;
treeNode *rightchild;
int element;
treeNode()
{
element=0;
leftchild=NULL;
rightchild=NULL;
}
treeNode(int element)
{
this->element=element;
leftchild=NULL;
rightchild=NULL;
}
treeNode(int element,treeNode* left,treeNode* right)
{
this->element=element;
leftchild=left;
rightchild=right;
}
};
class linkBT
{
public:
linkBT();
// ~linkeBT();
void input(int); //输入前序中序的
void postOrder(const treeNode*); //后序
treeNode* build(int,int,int,int); //二叉树的构建
void visit(const treeNode* t){cout<<t->element<<" ";}
private:
treeNode* root;
int* pre,*in; //用来装前 序和中序
};
linkBT::linkBT()
{
root=NULL;
pre = new int[10005];
in = new int[10005];
}
//后序
void linkBT::postOrder(const treeNode* t)
{
if(t!=NULL&&t->element!=-1)
{
postOrder(t->leftchild);
postOrder(t->rightchild);
visit(t);
}
}
//输入
void linkBT::input(int n)
{
int a;
for(int i=0;i<n;i++)
{
cin>>a;
pre[i]=a;
}
for(int i=0;i<n;i++)
{
cin>>a;
in[i]=a;
}
}
//构建
treeNode* linkBT::build(int s1,int e1,int s2,int e2)//s1指向pre,s2指向in,e1,e2是大小
{
root= new treeNode(pre[0]);
treeNode* root1 = new treeNode(pre[s1]);
int rootid;
for(int i=s2;i<=e2;i++)
{
if(in[i]==pre[s1])
{
rootid=i;
break;
}
}
if(rootid!=s2)
{
root1->leftchild=build(s1+1,s1+rootid-s2,s2,rootid-1);
}
if(rootid!=e2)
{
root1->rightchild=build(e1-e2+rootid+1,e1,rootid+1,e2);
}
return root1;
}
int main()
{
linkBT a;
int n;
cin>>n;
a.input(n);
treeNode* c = a.build(0,n-1,0,n-1);
a.postOrder(c);
cout<<endl;
}
接收二叉树前序序列和中序序列(各元素各不相同),输出该二叉树的后序序列。
格式
输入格式
输入有三行:
第一行为数字n。
第二行有n个数字,表示二叉树的前序遍历。
第三行有n个数字,表示二叉树的中序遍历。