实验9-2

#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个数字,表示二叉树的中序遍历。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值