理解《剑指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; }
相关文章推荐
- 《剑指Offer》面试题-重建二叉树
- 剑指Offer:面试题6重建二叉树
- 《剑指offer》面试题6:重建二叉树
- 剑指offer---面试题6重建二叉树
- (剑指Offer)面试题6:重建二叉树
- 剑指offer面试题7:重建二叉树 Java代码实现
- 剑指offer-面试题6.重建二叉树
- 剑指offer:面试题6--重建二叉树
- 《剑指Offer》面试题-重建二叉树
- 《剑指Offer》面试题6 重建二叉树——勘误
- 《剑指offer》(面试题6):重建二叉树
- 剑指offer_面试题6_重建二叉树(分解步骤,逐个击破)
- 剑指Offer(第二版)面试题7:重建二叉树
- 剑指offer面试题06 重建二叉树
- 剑指Offer面试题:5.重建二叉树
- 《剑指offer》面试题6:重建二叉树
- 剑指offer-面试题6 重建二叉树
- 剑指Offer-【面试题06:重建二叉树】
- 剑指offer面试题java实现之题6:重建二叉树
- 剑指offer 面试题6 重建二叉树