二叉树-----已知先序遍历、中序遍历,重建二叉树

博客围绕二叉树展开,核心是利用先序遍历和中序遍历的结果来重建二叉树,这在信息技术领域的数据结构处理中具有重要意义,涉及到对二叉树特性及遍历规则的运用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

struct BinaryTreeNode
{
	int value;
	BinaryTreeNode *Left;
	BinaryTreeNode *Right;
};

BinaryTreeNode *ConstructCore(int *startPreorder, int *endPreorder, int *startInorder, int *endInorder)
{
//创建一个结节点
	int rootValue = startPreorder[0];
	BinaryTreeNode* root = new BinaryTreeNode();
	root->value = rootValue;
	root->Left = root->Right = nullptr;
	if (startPreorder == endPreorder)
	{
		if (startInorder == endInorder && *startPreorder == *startInorder)
			return root;
		else
			throw std::exception("Invalid input.");
	}
//在中序遍历中找到根结点
	int *rootInorder = startInorder;
	while (startInorder <= endInorder && *rootInorder != rootValue)
		++rootInorder;
	if (rootInorder == endInorder && *rootInorder != rootValue)
		throw std::exception("Invalid Input.");
	int leftLength = rootInorder - startPreorder;
	int* leftPreorderEnd = startPreorder + leftLength;
	if (leftLength > 0)
	{
//构建左子树
		root->Left = ConstructCore(startPreorder + 1, leftPreorderEnd, startInorder, rootInorder - 1);
	}
//构建右子树
	if (leftLength < endPreorder-startPreorder)
	{
		root->Right = ConstructCore(leftPreorderEnd+1,endPreorder,rootInorder+1,endInorder);
	}
	return root;
}

BinaryTreeNode *Construct(int *preorder, int *inorder, int length)
{
	if (preorder == nullptr || inorder == nullptr || length <= 0)
		return nullptr;
	return ConstructCore(preorder, preorder + length - 1, inorder, inorder + length - 1);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值