剑指offer-面试题6
来源:互联网 发布:数组怎么输出 编辑:程序博客网 时间:2024/06/07 14:46
题目: 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
解题思路:递归实现
/*********************** 面试题6 : 重建二叉树***********************/struct BinaryTreeNode{intValue;BinaryTreeNode*pLeft;BinaryTreeNode*pRight; };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->Value = rootValue;root->pLeft = root->pRight = NULL;if(startPreorder == endPreorder){if(startInorder = endInorder && *startPreorder == *startInorder) return root;elsethrow exception("Invalid input");}// 在中序遍历序列中找到根节点的值int* rootInorder = startInorder;while(rootInorder <= endInorder && *rootInorder != rootValue){++rootInorder;}if(rootInorder == endInorder && *rootInorder != rootValue){throw exception("Invalid input");}int leftLength = rootInorder - startInorder;int* leftPreorderEnd = startPreorder +leftLength;if(leftLength > 0){//构建左子树root->pLeft = ConstructCore(startPreoder + 1, leftPreorderEnd, startInorder, rootInorder -1);}if(leftLength < endPreorder - startPreorder){//构建右子树root->pRight = ConstructCore(leftPreorderEnd + 1,endPreorder, rootInorder + 1, endInorder);}return root;}
0 0
- 剑指offer面试题6
- 剑指offer 面试题6
- 剑指offer-面试题6
- 【面试题】剑指offer 6
- 剑指offer 面试题
- 剑指offer面试题
- 剑指Offer(面试题6~7)
- 剑指Offer面试题6 & Leetcode105
- 剑指offer面试题总结
- 剑指offer面试题06
- 剑指offer面试题 04
- 剑指offer 面试题07
- 剑指offer面试题08
- 剑指offer面试题42
- 剑指offer面试题1
- 剑指offer面试题3
- 剑指offer面试题4
- 剑指offer面试题5
- JAVA的文件操作
- Mysql通过source执行一个sql文件
- Activiti(四)——流程变量的设置和获取
- java基本排序之简单选择排序
- HIHO Trie图 (ac自动机入门)
- 剑指offer-面试题6
- n个数中取出r个数组合,逆序输出 组合数
- 暗黑修仙 页游 架设教程 单机 自玩 一键端
- Git相比较SVN有哪些优点
- Java的文件读写操作
- 位操作小结与宏定义
- 进程间通信笔记-记录上锁&&信号量&&共享内存
- TCP/UDP区别以及UDP如何实现可靠传输
- Activiti(五)——流程执行历史记录