输入某二叉树的前序遍历和中序遍历的结果,重建该二叉树。
假如输入的前序遍历和中序遍历的结果都不含重复的数字。
前序遍历:{1,2,3,7,3,5,6,8}
中序遍历:{4,7,2,1,5,3,8,6}
重建二叉树并输出头结点。
struct BinaryTreeNode
{
int nValue;
BinaryTreeNode* pLeft;
BinaryTreeNode* pRight;
};
BinaryTreeNode* ConstructCore(int* startPreorder, int* endPreorder, int* startInorder, int* endInorder);
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->nValue=rootvalue;
root->pLeft = root->pRight =NULL;
if(startPreorder == endPreorder)
{
if(startInorder == endInorder && *startPreorder == * startInorder)
return root;
else
throw std::exception("Invalid input.");
}
int* rootInorder =startInorder;
while(rootInorder <= endInorder && *rootInorder != rootvalue)
++ rootInorder;
if(rootInorder == endInorder && *rootInorder != rootvalue)
throw std::exception("Invalid input.");
int leftLength = rootInorder - startInorder;
int* leftPreorderEnd = startPreorder + leftLength;
if (leftLength >0)
{
root->pLeft = ConstructCore(startPreorder + 1,leftPreorderEnd, startInorder, rootInorder - 1);
}
if(leftLength< endPreorder - startPreorder)
{
root->pRight= ConstructCore(leftPreorderEnd + 1, endPreorder, rootInorder + 1, endInorder);
}
return root;
}