《剑指Offer》学习笔记——重建二叉树
2016-04-05 20:16
344 查看
题目描述:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
参考:http://blog.csdn.net/sunnyyoona/article/details/46966143
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
#include <vector> #include <string> #include <algorithm> using namespace std; struct TreeNode{ int val; TreeNode *left; TreeNode *right; TreeNode(int x):val(x),left(nullptr),right(nullptr){} }; class Solution{ public: struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) { int size = pre.size(); if(size == 0){ return nullptr; } return PreInBuildTree(pre,in,0,0,size); } private: TreeNode* PreInBuildTree(vector<int> preorder,vector<int> inorder,int preIndex,int inIndex,int size){ if(size == 0){ return nullptr; } // 根节点 TreeNode* root = new TreeNode(preorder[preIndex]); // 寻找根节点在中序遍历数组的下标 int index = 0; for(int i = 0;i < size;++i){ // 注意:inorder[inIndex+i] if(preorder[preIndex] == inorder[inIndex+i]){ index = inIndex+i; break; } } // 左子树个数 int leftSize = index - inIndex; // 右子树个数 int rightSize = size - leftSize - 1; // 左子树 root->left = PreInBuildTree(preorder,inorder,preIndex+1,inIndex,leftSize); // 右子树 root->right = PreInBuildTree(preorder,inorder,preIndex+1+leftSize,index+1,rightSize); return root; } };
参考:http://blog.csdn.net/sunnyyoona/article/details/46966143
相关文章推荐
- CSS滑动门特性
- codeforces_620D. Professor GukiZ and Two Arrays
- 隐藏(删除) Preference 小结
- coffeeScript demo
- Caffe——清晰高效的深度学习(Deep Learning)框架
- 前端开发知识点总结
- 前端开发知识点总结
- ReactNative学习九-登录页面
- 安卓可以调js的方法,可js调不了安卓的方法之解决方法
- 前端开发知识点总结
- BootStrap之基础-4 插件(JS插件)
- js中clone的运用和clone后datepicker的显示问题
- 【poj 2492】A Bug's Life 题意&题解&代码(C++)
- [poj 2492 ] A Bug's Life 并查集应用
- css transform 详解
- JavaScript array对象的方法
- CSS3 animation 属性详解
- CSS样式
- ReactNative学习八-搜索栏的基本布局
- 浅读Caffe: Blobs, Layers, and Nets