您的位置:首页 > 职场人生

理解《剑指Offer》之面试题6 重建二叉树

2014-11-15 20:37 465 查看
最近在看《剑指Offer》这本书,由于基础不好,所以把现在我看懂得书中的源代码每行都增加了我所理解的注释了,仅供基础像我一样的童靴理解书中的代码,可能我是画蛇添足了,呵呵
前序遍历:
1   2   4   7   3   5   6   8
中序系列:
4   7   2   1   5   3   8   6
 二叉树数据结构:

struct BinaryTreeNode
{
int                         m_Value;     //节点值
BinaryTreeNode* m_LeftTree;   //左子树指针
BinaryTreeNode* m_RightTree;   //右子树指针

};

构建二叉树:

BinaryTreeNode* ConstructCore(
int *startPreorder,        //指向前序序列中的第一个元素的指针
int *endPreorder,         //  指向前序序列的最后一个元素的指针
int *startInorder,       //   指向中序序列的第一个元素的指针
int *endInorder          //    指向中序序列的最后元素的指针
);

BinaryTreeNode* Construct(
int *preorder, //指向前序序列的指针
int *inorder,  //指向中序序列的指针
int lenght     // 序列的长度
)
{
if (preorder==NULL||inorder==NULL||lenght==0)
{
return NULL;
}
return ConstructCore(preorder, preorder + lenght - 1, inorder, inorder + lenght - 1);
}

BinaryTreeNode* ConstructCore(
int *startPreorder,        //指向前序序列中的第一个元素的指针
int *endPreorder,         //  指向前序序列的最后一个元素的指针
int *startInorder,       //   指向中序序列的第一个元素的指针
int *endInorder          //    指向中序序列的最后元素的指针
)
{
int rootValue = startPreorder[0];
BinaryTreeNode* root = new BinaryTreeNode();
root->m_Value = rootValue;
root->m_RightTree = root->m_LeftTree = NULL;

if (startPreorder==endPreorder)  //只有一个节点root
{
if (startInorder==endInorder
&& *startPreorder==*startInorder
)
{
return root;
}
else{
throw exception("Invalid input.");

}

}
//在中序遍历中找到根节点的值
int *rootInorder = startInorder;   //从中序序列的第一个元素开始
while (rootInorder<=endInorder&& *rootInorder!=rootValue)//遍历查找在中序中的根节点的位置
{
++rootInorder;

}
if (rootInorder==endInorder&&*rootInorder!=rootValue)//遍历整个序列没有找到根节点
{
throw exception("invaild input.");

}
int LeftLenght = rootInorder - startInorder;  //计算左子树的元素个数
int *LeftPreorderEnd = startPreorder + LeftLenght;  //在前序序列中找到左子树的最后一个节点
if (LeftLenght>0)//递归构造左子树
{
root->m_LeftTree = ConstructCore(
startPreorder + 1,   //左子树的根是根节点的下一个节点(前序序列)
LeftPreorderEnd,    //左子树的最后一个元素
startInorder,       //中序序列中在根节点之前的都是属于左子树
rootInorder - 1     //中序序列中左子树的最后一个节点
);

}
if (LeftLenght < endPreorder - startPreorder)
{
root->m_RightTree = ConstructCore(LeftPreorderEnd + 1, endPreorder, rootInorder + 1, endInorder);
}
return root;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: