剑指offer编程题——06 重建二叉树

#include<iostream>
using namespace std;
struct BinaryTreeNode{
	int m_value;
	BinaryTreeNode* m_left;
	BinaryTreeNode* m_right;
};
BinaryTreeNode* ConstructCore(int* startPre, int* endPre, 
						      int* startIn,  int* endIn){
	int rootv = startPre[0];
	BinaryTreeNode* root = new BinaryTreeNode();
	root->m_value = rootv; 
	root->m_left = root->m_right = NULL;
	if (startPre == endPre){ //序列中只有一个值
		if (startIn == endIn && *endPre == *endIn)
			return root;
		else
			throw exception("Invalid input!");
	}
	
	int *rootIn = startIn;
	while (rootIn != endIn && *rootIn != rootv)
		++rootIn;
	if (rootIn == endIn && *rootIn != rootv) //序列中有多个值
		throw exception("Invalid input!");
	int leftlen = rootIn - startIn;
	int *leftend = startPre + leftlen;
	if (leftlen > 0)
		root->m_left = ConstructCore(startPre + 1, leftend, startIn, rootIn - 1);
	if (leftlen < endPre - startPre)
		root->m_right = ConstructCore(leftend + 1, endPre, rootIn + 1, endIn);
	return root;
}
BinaryTreeNode* Construct(int* preorder, int* inorder, int len){
	if (preorder == NULL || inorder == NULL || len <= 0)
		return NULL;
	return ConstructCore(preorder, preorder + len - 1, inorder, inorder + len - 1);
}
// ====================测试代码====================
void main06(){
	//const int length = 8;
	//int pre[length] = { 1, 2, 4, 7, 3, 5, 6, 8 };
	//int in[length] = { 4, 7, 2, 1, 5, 3, 8, 6 };
	//const int length = 5;
	//int preorder[length] = { 1, 2, 3, 4, 5 };
	//int inorder[length] = { 5, 4, 3, 2, 1 };
	//const int length = 5;
	//int preorder[length] = { 1, 2, 3, 4, 5 };
	//int inorder[length] = { 1, 2, 3, 4, 5 };
	//const int length = 1;
	//int preorder[length] = { 1 };
	//int inorder[length] = { 1 };
	const int length = 7;
	int preorder[length] = { 1, 2, 4, 5, 3, 6, 7 };
	int inorder[length] = { 4, 2, 8, 1, 6, 3, 7 };
	BinaryTreeNode* root = Construct(preorder, inorder, length);
	if (root != nullptr){
		printf("root value: %d\n", root->m_value);
		if (root->m_left != NULL)
			printf("root->left value: %d\n", root->m_left->m_value);
		if (root->m_right != NULL)
			printf("root->right value: %d", root->m_right->m_value);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值