已知中序与后序,或者中序与先序,构造二叉树

示例代码:

#include<iostream>
using namespace std;
struct BTNode
{
 int key;
 BTNode *lchild;
 BTNode *rchild;
};
BTNode * constructtree1(int *spre,int *epre,int *sinorder,int *einorder) //已知先序、中序求后序
{
  int rootValue=spre[0];
  BTNode *r=new BTNode();
  r->key=rootValue;
  r->lchild=r->rchild=NULL;

  int *rootInorder=sinorder;
  while(rootInorder<=einorder && *rootInorder!=rootValue)
   ++rootInorder;
  int length=rootInorder-sinorder;
  int * leftpreorderEnd=spre+length;
  if(length>0)
  {
   r->lchild=constructtree1(spre+1,leftpreorderEnd,sinorder,rootInorder-1);
  }
  if(length<epre-spre)
  {
   r->rchild=constructtree1(leftpreorderEnd+1,epre,rootInorder+1,einorder);
  }
  return r;
}
BTNode *constructtree2(int *sinorder,int *einorder,int *epostorder,int *spostorder) //已知后序、中序求先序
{
   int rootValue=epostorder[0];
   BTNode * root=new BTNode();
   root->key=rootValue;
   root->lchild=root->rchild=NULL;
   int * rootInorder=sinorder;
   while(rootInorder<=einorder && *rootInorder!=rootValue)
    ++rootInorder;
   int length=rootInorder-sinorder;
   if(length>0)
   {
    root->lchild=constructtree2(sinorder,rootInorder-1,spostorder+length-1,spostorder);
   }
   if(length<epostorder-spostorder)
   {
    root->rchild=constructtree2(rootInorder+1,einorder,epostorder-1,spostorder+length);
   }
 return root;
}
void preorder(BTNode *r)
{
 if(r==NULL)
  return;
 cout<<r->key<<endl;
 preorder(r->lchild);
 preorder(r->rchild);
}
int main()
{
    int a[10]={1,2,4,7,3,5,6,8};
 int b[10]={4,7,2,1,5,3,8,6};
 int c[10]={7,4,2,5,8,6,3,1};
 BTNode *s;
 //s=constructtree1(a,a+7,b,b+7);
 s=constructtree2(b,b+7,c+7,c);
 preorder(s);
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值