使用前序和中序遍历重构二叉树

#include<iostream>
using namespace std;
struct BiNode
{
	int value;
	BiNode * lchild;
	BiNode * rchild;
}node;
typedef BiNode *Btree;
//参数代表遍历子树的起始位置
Btree rebuild(int preOrder[], int startpre, int endpre, int inOrder[], int startin, int endin)
{
	//前序和中序两者长度应该相等
	if (endpre - startpre != endin - startin) return NULL;
	if (startpre - endpre > 0) return NULL;
	Btree tree = new BiNode;
	tree->value = preOrder[startpre];
	tree->lchild = NULL;
	tree->rchild = NULL;
	//只有一个节点
	if (startpre == endpre) return tree;
	int index, length;
	//在中序遍历中找到根节点
	for (index = startin; index <= endin; index++)
	{
		if (inOrder[index] == preOrder[startpre]) break;
	}
	//未找到,返回空
	if (index > endin)
	{
		return NULL;
	}
	//index代表中遍历中根节点的下标,若index>startin,则代表有左子树,递归调用构建左子树
	if (index > startin)
	{
		//现在length代表了左子树结点的个数
		length = index - startin;
		//将下标定位到左子树的根节点
		tree->lchild = rebuild(preOrder, startpre + 1, startpre + 1 + length - 1, inOrder, startin, startin + length - 1);
    }
	if (index < endin)
	{
		length = endin - index;
		//将下标定位到右子树的根节点
		tree->rchild = rebuild(preOrder, endpre - length + 1, endpre, inOrder, endin - length + 1, endin);
	}
	return tree;
}
void postTraverse(Btree tree)
{
	if (tree->lchild != NULL) postTraverse(tree->lchild);
	if (tree->rchild != NULL) postTraverse(tree->rchild);
	cout << tree->value;
}
int main()
{
	int preOrder[] = { 1,2,4,5,3,6 };
	int inOrder[] = { 4,2,5,1,6,3 };
	Btree tree = rebuild(preOrder, 0, 5, inOrder, 0, 5);
	postTraverse(tree);
	return 0;
}

其实根据前序和中序的特点就可以做了,前序的第一个元素必定是根节点,那么在中序的序列中查找这个根节点的位置,两侧分为两部分,递归下去即可。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值