假设输入二叉树的前序遍历序列为{1,2,4,7,3,5,6,8},中序遍历序列{4,7,2,1,5,3,8,6}
思路:
首先由前序遍历序列可以找到根结点的值是第一个元素的值,然后去寻找中序遍历中根结点的位置在哪里,从而可以得到左子树的长度大小,可以确定前序遍历中左子树的终点位置在哪里,就可以重新构建左子树。同时,由中序遍历中根结点的位置和前序遍历中左子树的终点位置重构右子树。
代码实现如下:
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
}
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_pLeft=root->m_pRight=NULL;
if(startPreorder==endPreorder)
{
if(startInorder==endInorder && *startPreorder==*startInorder)
return root;
else
throw std::exception("Invalid inout.");
}
//中序遍历中找到根结点的值
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->m_pLeft=ConstructCore(startPreorder+1,leftPreorderEnd,startInorder,rootInorder-1);
}
if(leftlength<endPreorder-startPreorder)
{
//构建右边子树
root->m_pRight=ConstructCore(leftPreorderEnd+1,PreorderEnd,rootInorder+1,endInorder);
}
}