输入某二叉树的前序遍历和中序遍历的结果,重建该二叉树。
假如输入的前序遍历和中序遍历的结果都不含重复的数字。
前序遍历:{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;
}
本文介绍了一种通过前序遍历和中序遍历结果来重建二叉树的方法,并提供了具体的C++实现代码。该方法首先从给定的前序遍历序列中找到根节点,再在中序遍历序列中定位根节点位置,从而划分出左子树和右子树的元素范围,递归地构造整个二叉树。
875

被折叠的 条评论
为什么被折叠?



