剑指offer——面试题6:重建二叉树
来源:互联网 发布:软件模块化设计 实例 编辑:程序博客网 时间:2024/06/09 14:30
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->m_pLeft = root->m_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->m_pLeft = ConstructCore(startPreorder + 1, leftPreorderEnd, startInorder, rootInorder - 1); } if(leftLength < endPreorder - startPreorder) { // 构建右子树 root->m_pRight = ConstructCore(leftPreorderEnd + 1, endPreorder, rootInorder + 1, endInorder); } return root;}
0 0
- 剑指offer——面试题6:重建二叉树
- 剑指offer——面试题6:重建二叉树
- 剑指offer 面试题6—重建二叉树
- 剑指offer 面试题6—重建二叉树
- 《剑指Offer》面试题-重建二叉树
- 【剑指offer】2.3.4树——面试题6:重建二叉树
- 剑指Offer:面试题6——重建二叉树(java实现)
- 剑指offer--面试题6: 重建二叉树(树)
- 剑指offer-->面试题6 重建二叉树
- 【剑指offer】面试题6:重建二叉树
- 《剑指offer》面试题6:重建二叉树
- 剑指offer 面试题6 重建二叉树
- 剑指Offer:面试题6 重建二叉树
- 《剑指offer》面试题6:重建二叉树
- 《剑指offer》面试题6重建二叉树
- 剑指offer面试题6--重建二叉树
- 理解《剑指Offer》之面试题6 重建二叉树
- 剑指offer 面试题6 重建二叉树
- Spring整合log4j日志组件
- Unity3D自学笔记——星际2技能系统分析(四)Ability(Behavior)
- golang程序在windows上,注册为服务
- CSS样式基础
- firefox 网页编码
- 剑指offer——面试题6:重建二叉树
- cs231n:assignment1——Q3: Implement a Softmax classifier
- UE4读取scv文件 -- 数据驱动游戏性元素
- form 表单提交submit 和 ajax 混用可能导致后台 错误
- iOS怎么处理网络请求json中的null
- 在android view中写坦克大战
- 周总结-20161125
- 使用CSS3实现加载中动画
- Android30分钟 DIY搭建局域网视频直播演示Demo