题目6:重建二叉树
题目:输入某二叉树的前序遍历和中序遍历的结果,重建出该二叉树。
解题的过程:
我们知道根据二叉树的前序或者后序遍历的结果,加上中序遍历的结果便可以还原出这棵二叉树。
例如:前序序列为:
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
4 | 7 | 2 | 1 | 5 | 3 | 8 | 6 |
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);
}
BinaryTreeeNoe * ConstructCore
(int * startPreorder,int * endPreorder,int * startInorder,int * endInorder)
{
int rootValue = startPreorder[0];
BinaryTreeNode * root = new BinaryTreeNode();
root->value = rootValue;
root->Left = root->Right=null;
if(startPreorder == endPreorder)
{
if(startInorder == endInorder && *startPreoder==*startInorder)
{
return root;
}
else
{
exception("error");
}
}
//在中序遍历中找到根节点的值
int * rootInorder = startInorder;
while(rootInorder <= endInorder && *rootInorder != rootValue)
{
++ rootInorder;
}
if(rootInorder == endInorder && *rootInorder != rootValue)
{
exception("error");
}
int leftLength = rootInorder - startInorder;
int * leftPreorderEnd = startInorder +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);
}
return root;
}
现在理解的还不是太透彻继续领悟。