LeetCode *** 106. Construct Binary Tree from Inorder and Postorder Traversal
2016-04-18 08:56
489 查看
题目:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
分析:
我都不知道怎么回事,出错次数太多了,搞得自己都没信心了。
代码:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
分析:
我都不知道怎么回事,出错次数太多了,搞得自己都没信心了。
代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { if(inorder.empty()||inorder.size()!=postorder.size())return NULL; int val=*(postorder.end()-1); TreeNode* root=new TreeNode(val); int i=0; while(inorder[i]!=val)i++; root->left=buildTree(inorder,0,i-1,postorder,0,i-1); root->right=buildTree(inorder,i+1,inorder.size()-1,postorder,i,inorder.size()-2); return root; } TreeNode* buildTree(vector<int>& inorder,int is,int ie, vector<int>& postorder,int ps,int pe){ if(is>ie)return NULL; int val=postorder[pe]; TreeNode* root=new TreeNode(val); int i=is; while(inorder[i]!=val)i++; root->left=buildTree(inorder,is,i-1,postorder,ps,ps+i-is-1); root->right=buildTree(inorder,i+1,ie,postorder,ps+i-is,pe-1); return root; } };
相关文章推荐
- Linux下修改MAC地址
- 软件开发网站推荐
- 软件设计模式——命令模式(Command Pattern)
- ArcGIS Javascript学习笔记(一)arcgis API 的本地部署
- svn在主干上创建分支
- [转]DES加密解密工具2.1及其代码——支持字符串及文件加密,支持3重DES
- 利用R语言进行线性/非线性回归拟合实例(1)
- HTML+CSS学习笔记
- OK335xS psplash make-image-header.sh hacking
- JS基于MSClass和setInterval实现ajax定时采集信息并滚动显示的方法
- HighCharts点击柱形或饼块加URL或Click事件
- mysql timeout expired处理
- 053(二十八)
- 那些著名或非著名的iOS面试题-前编
- 053(二十七)
- tomcat 日志输出
- Android studion下载GsonFormat插件
- iOS基于MVC的项目重构总结
- JAVA 模拟浏览器请求
- 基于标记的AR的OpenCV实现(二)