思路:前序第一个元素作为根,从中序找出左子树和右子树的序列,递归构建子树
TreeNode * Construct(int * preOrder,int * inOrder,int length)
{//根据前序和中序构造二叉树
if (preOrder==NULL||inOrder==NULL||length<=0)
{
return NULL;
}
return ConstructCore(preOrder,preOrder+length-1,inOrder,inOrder+length-1);
}
TreeNode * ConstructCore(int* startPreOrder,int* endPreOrder,int* startInOrder,int* endInOrder)
{
int rootValue=startPreOrder[0];
TreeNode* root=new TreeNode();
root->value=rootValue;
root->lchild=root->rchild=NULL;
if (startPreOrder==endPreOrder)
if (startInOrder==endInOrder&&(*startPreOrder)==(*startInOrder))
{
return root;
}
else throw std::exception("error");
//寻找根在中序中的位置
int * rootInOrder=startInOrder;
while(rootInOrder<=endInOrder&&*rootInOrder!=rootValue) rootInOrder++;
if (rootInOrder==endInOrder&&*rootInOrder!=*endInOrder) throw std::exception("error");
int leftLength=rootInOrder-startInOrder;
int rightLength=endInOrder-rootInOrder;
int* leftEndPreOrder=startPreOrder+leftLength;
int* rightStartPreOrder=leftEndPreOrder+1;
if (leftLength>0)
{//构建左子树
root->lchild=ConstructCore(startPreOrder+1,leftEndPreOrder,startInOrder,rootInOrder-1);
}
if (rightLength>0)
{
root->rchild=ConstructCore(rightStartPreOrder,endPreOrder,rootInOrder+1,endInOrder);
}
return root;
}