重建二叉树
来源:互联网 发布:adobe encoder mac 编辑:程序博客网 时间:2024/06/05 16:29
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
class Solution {public: TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { if (pre.size() < 0 || vin.size() <0 || pre.size() != vin.size()) { return NULL; } return reConstructBinaryCore(pre, 0, pre.size()-1,vin, 0,vin.size()-1); } TreeNode* reConstructBinaryCore(vector<int> pre,int startPre,int endPre, vector<int> vin,int startIn, int endIn) { int rootvalue = pre[startPre]; TreeNode* root = new TreeNode(rootvalue); int InRoot = startIn; while (InRoot <= endIn && vin[InRoot] != rootvalue) { InRoot++; } int leftlenth = InRoot - startIn; if (leftlenth > 0) { root->left = reConstructBinaryCore(pre, startPre + 1, startPre + leftlenth, vin, startIn, startIn + leftlenth - 1); } if (endPre - startPre >leftlenth) { root->right = reConstructBinaryCore(pre, startPre + leftlenth + 1, endPre, vin,startIn + leftlenth + 1, endIn); } return root; }};
阅读全文
0 0
- 3.9重建二叉树
- 重建二叉树
- 二叉树重建
- 二叉树重建
- 二叉树的重建
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 二叉树重建
- 二叉树重建
- 重建二叉树
- 重建二叉树
- 重建二叉树
- poj3437
- 《JavaScript语言精粹》笔记
- 倍增法求最近公共祖先(LCA)
- spring技术内幕笔记:ApplicationContext和Bean的初始化及销毁
- kafka的数据发送和接收java_API
- 重建二叉树
- rem
- PLSA主题模型的EM算法推导
- HFOI2017.7.15校内赛(普及组)题解
- Machine Learning 之 Types of Learning
- [记录]Java虚拟机 - 待续
- Lintcode87 Remove Node In Binary Search Treesolution 题解
- 携程Android App插件化和动态加载实践
- jenkins上的常用插件