LeetCode(106) Construct Binary Tree from Inorder and Postorder Traversal
2015-10-17 13:14
513 查看
题目
Given inorder and postorder traversal of a tree, construct the binary tree.Note:
You may assume that duplicates do not exist in the tree.
Show Tags
Show Similar Problems
分析
跟上一道题同样的道理。AC代码
class Solution { public: template <typename Iter> TreeNode* make(Iter in_begin, Iter in_end , Iter post_begin, Iter post_end ) { if (post_begin == post_end || in_begin == in_end) return NULL; int size = post_end - post_begin; //后序遍历最后一个节点为树的根节点 TreeNode *root = new TreeNode(*(post_begin + size-1)); //在中序遍历结果中查找根节点 Iter iter = find(in_begin, in_end, *(post_begin + size - 1)); //计算左子树个数 int count = iter - in_begin; if (iter != in_end) { //则在inOrder中(0 , count-1)为左子树中序遍历结果(count+1,size-1)为右子树的中序遍历序列 //在preOrder中(0,count-1)为左子树前序遍历结果(count,size-2)为右子树前序遍历结果 root->left = make(in_begin, iter , post_begin, post_begin + count); //构造右子树 root->right = make(iter + 1, in_end ,post_begin + count, post_begin + size - 1); } return root; } TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { if (inorder.empty() || postorder.empty()) return NULL; return make(inorder.begin(), inorder.end() ,postorder.begin(), postorder.end()); } };
GitHub测试程序源码
相关文章推荐
- C#中 委托和事件的关系
- LeetCode(106) Construct Binary Tree from Inorder and Postorder Traversal
- leetcode Merge Two Sorted Lists
- fsockopen模拟post,get发送请求
- iOS开发之仿微信小视频功能实现
- 大道至简读后感
- 未来10年房地产存量与人口需求量分析
- jQuery页面加载方法
- 程序媛人生——专访“龙书”联合作者Monica S. Lam
- Quarts 设置每隔一定时间,执行一定次数
- Vbox中Linux虚拟机网络配置
- Gradle 10分钟上手指南
- <stl>list::sort源码分析
- LeetCode OJ:Contains Duplicate(是否包含重复)
- 1008. 数组元素循环右移问题 (20)
- 黑马程序员-- 核心语法 Property synthesize 成员变量的作用域
- 配置GitLab 用smtp发邮件 (gitlab-6.7.3)(系统环境 centos 6.7)
- 安卓通过marginBotton是如何隐藏线条的原理小分析
- 教你如何发布自己的网站
- delphi7和XE下 获取路径