struct BinaryTreeNode{
int m_nValue;
BinaryTreeNode* m_nLeft;
BinaryTreeNode* m_nRight;
};
BinaryTreeNode* 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);
}
BinaryTreeNode* ConstructCore(int* startPreorder,int* endPreorder,int* startInorder,int* endInorder){
int rootValue=startPreorder[0]; //第一个值为根节点
BinaryTreeNode* root=new BinaryTreeNode();
root->m_nValue=rootValue;
root->m_nLeft=root->m_nRight=NULL; //构建节点
if(startPreorder=endPreorder){
if(startInorder=endInorder&&*startPreorder=*startInorder) //只有一个结点的时候
return root;
else
throw exception("Invalid Input");
}
int* rootInorder=startInorder;
while(rootInorder<=endInorder&&*rootInorder!=rootValue) //在中序遍历中找到根节点
++rootInorder;
if(rootInorder==endInorder&&*rootInorder!=rootValue) //找到最后一点也不是要找的值则输入有误
throw exception("Invalid Input");
int leftLength=rootInorder-startInorder;
int* leftPreorderEnd=startPreorder+leftLength;
if(leftLength>0){
root->m_nLeft=ConstructCore(startPreorder+1,leftPreorderEnd,startInorder,rootInorder-1);
}
if(leftLenth<endPreorder-startPreorder)
root->m_nRight=ConstructCore(leftPreorderEnd+1,endPreorder,rootInorder+1,endInorder);
}
}