重建二叉树

  描述:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
  例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
  时间:2019-07-28 13:30
  函数名:printListFromTailToHead
  在前序遍历的数组中依次查找根节点,记录其值,利用该值,在中序遍历的数组中进行遍历查找,划分出二叉树的左、右子树。依次交替进行,直至前序遍历和中序遍历各自的首、尾指针指向同一个位置,且对应的值相同时,递归结束。
图示:
在这里插入图片描述
  最终结果:
在这里插入图片描述

struct BinaryTreeNode
{
	int m_nValue;
	BinaryTreeNode* m_pLeft;
	BinaryTreeNode* m_pRight;
};

BinaryTreeNode * Buynode()
{
	BinaryTreeNode *s = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode));
	if (NULL == s) exit(1);
	memset(s, 0, sizeof(BinaryTreeNode)); // new;
	return s;
}

void InOrder(BinaryTreeNode *p)
{
	if (NULL != p)
	{
		InOrder(p->m_pLeft);
		cout << p->m_nValue <<" ";
		InOrder(p->m_pRight);
	}
}

BinaryTreeNode* constructCore(int *prestart, int *preend, int *instart, int *inend)
{
	int rootvalue = prestart[0];  //根节点

	BinaryTreeNode* root = Buynode();  //根节点赋初值
	root->m_nValue = rootvalue;
	root->m_pLeft = root->m_pRight = NULL;

	if (prestart == preend)
	{
	
		if (instart == inend && *prestart == *instart)   //递归退出的条件  指针指向的值也相同
		{
			return root;
		}
		else
		{
			throw exception("无效的输入");  //遍历数组输入有误
		}
	}

	int *rootInorder = instart;            //rootInorder指向中序遍历数组的起始位置
	while (rootInorder <= inend && *rootInorder != rootvalue)   //中序遍历数组中查找递归的根节点
	{
		++rootInorder;
	}

	if (rootInorder == inend && *rootInorder != rootvalue)
	{
		throw exception("无效的输入");
	}

	int leftLength = rootInorder - instart;
	int *leftPreorderEnd = prestart + leftLength;  //前序遍历左子树的结尾

	if (leftLength > 0)
	{
		//构建左子树
		root->m_pLeft = constructCore(prestart + 1, leftPreorderEnd, instart, rootInorder - 1);
	}
	if (leftLength < preend - prestart)
	{
		//构建右子树
		root->m_pRight = constructCore(leftPreorderEnd + 1, preend, rootInorder + 1, inend);
	}

	return root;
}

BinaryTreeNode* reConstructBinaryTree(int pre[], int in[], int length)
{
	if (NULL == *pre || NULL == in || length <= 0)
	{
		return NULL;
	}

	return constructCore(pre, pre + length - 1, in, in + length - 1);
}

int main()
{
	int preorder[] = { 1, 2, 4, 7, 3, 5, 6, 8 };
	int infixorder[] = { 4, 7, 2, 1, 5, 3, 8, 6 };

	int length = sizeof(preorder) / sizeof(preorder[0]);


	BinaryTreeNode* root = reConstructBinaryTree(preorder, infixorder, length);

	InOrder(root);
	cout << endl;

	return 0;
}

  运行结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值