面试题重建二叉树

题目:已知二叉树的前序遍历和中序遍历结果,重建二叉树。假设不出现重复值的树节点。

#include <iostream>
using namespace std;

typedef struct BSTree 
{
	int val;
	BSTree*leftchild;
	BSTree*rightchild;
}*BSTreePoint;

BSTree *constructCore(int *preStart,int *preEnd,int *inorderStart,int *inorderEnd);

BSTree *construct(int *preorder,int *inorder,int len)
{
	if (preorder==NULL||inorder==NULL||len<1)
	{
		cout<<"构造条件错误\n";
	}
	return constructCore(preorder,preorder+len-1,inorder,inorder+len-1);
}

BSTree *constructCore(int *preStart,int *preEnd,int *inorderStart,int *inorderEnd)
{
	int rootValue=preStart[0];
	BSTree *root=new BSTree;
	root->val=rootValue;
	root->leftchild=root->rightchild=NULL;
	if (preStart==preEnd)
	{
		if ((inorderStart==inorderEnd)&&(*preStart==*inorderStart))
//递归到子树只有一个节点情况,如果前序和中序值不相等为非法输入
		{
			return root;//递归结束条件
		}
		else
		{
			cout<<"Invalid input order \n";
		}
	}
	int *rootInorder=inorderStart;
	while (rootInorder<=inorderEnd&&*rootInorder!=rootValue)
	{
		rootInorder++;
	}
	if (rootInorder>inorderEnd)
	{
		cout<<"Invalid input \n";
	}
	int leftlen=rootInorder-inorderStart;
	int *preleftEnd=preStart+leftlen;
	if (leftlen>0)
	{
		//递归建左子树
		root->leftchild=constructCore(preStart+1,preleftEnd,inorderStart,rootInorder-1);
	}
	if (leftlen<(preEnd-preStart))//如果右子树有节点
	{
		root->rightchild=constructCore(preStart+leftlen+1,preEnd,rootInorder+1,inorderEnd);
	}
	return root;
}

void PreOrder(BSTree *root)
{
	if (root!=NULL)
	{
		cout<<root->val<<" ";
		PreOrder(root->leftchild);
		PreOrder(root->rightchild);
	}	
}

void InOrder(BSTree *root)
{
	if (root!=NULL)
	{
		InOrder(root->leftchild);
		cout<<root->val<<" ";
		InOrder(root->rightchild);
	}
}

int main()
{
	int pre[]={1,2,4,7,3,5,6,8};
	int inorder[]={4,7,2,1,5,3,8,6};
	BSTree *root=construct(pre,inorder,8);
	PreOrder(root);
	cout<<endl;
	InOrder(root);
	cout<<endl;
}


思想来源于:剑指offer ,感谢作者。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值