题目是这样的:给出二叉树的前序遍历和后序遍历结果,存储在整型数组中。据此构建出该二叉树。
思路分析:主要考虑到遍历的特点,可以参考之前的一篇博客。我们可以根据前序遍历结果找到根节点,也就是前序遍历结果的第一个元素,然后在中序遍历结果中找到根节点,那么根节点的左边的元素就是左子树,右边的就是右子树,进而对这两部分递归构建~~
下面是代码,看一遍应该没问题的~~
//二叉树结点
struct BinaryTreeNode {
int m_nValue;
BinaryTreeNode* left;
BinaryTreeNode* right;
};
/************************************************************************/
/* 重建二叉树:
题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
*/
/************************************************************************/
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->right = root->left = 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->left = ConstructCore(startPreorder + 1, leftPreorderEnd, startInorder, rootInorder - 1);
}
if (leftLength < endPreorder - startPreorder) {
//构建右子树
root->right = ConstructCore(leftPreorderEnd + 1, endPreorder, rootInorder + 1, endInorder);
}
root;
}