输入某二叉树的前序和中序遍历结果,重建该二叉树

/*
输入某二叉树的前序和中序遍历结果,重建该二叉树
*/
文中的前序遍历函数是为了验证重建的二叉树是否正确
#include <iostream>
using namespace std;
struct tree
{
int value;
tree *left;
tree *right;
};
tree *constructCore(int *s1,int *e1,int *s2,int *e2)
{
tree *root = new tree;
root->value = s1[0];
root->left = NULL;
root->right = NULL;
if (s1 == e1)
{
if(s2 == e2 && *s1 == *s2)
return root;
}
int  *p = s2;
while(p<=e2 && *p!= s1[0])
{
p++;
}
int len_l = p-s2;
int len_r = e2-p;
int *new_e1 = s1+len_l;
if(len_l>0)
{
root->left = constructCore(s1+1,new_e1,s2,s2+len_l-1);
}
if (len_r>0)
{
root->right = constructCore(new_e1+1,e1,p+1,e2);
}
return root;


}
tree *construct(int *pr,int *ino,int len)
{
if (pr==NULL||ino==NULL||len<=0)
{
return NULL;
}
return constructCore(pr,pr+len-1,ino,ino+len-1);
}


void pre(tree *root)
{
if(root!=NULL)
{
cout<<root->value<<endl;
pre(root->left);
pre(root->right);
}
}
int main()
{
int s1[] = {1,2,4,7,3,5,6,8};
int s2[] = {4,7,2,1,5,3,8,6};
tree *root = construct(s1,s2,8);
pre(root);
return 0;




}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值