[LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
2015-12-11 10:30
483 查看
题目描述:(链接)
Given inorder and postorder traversal of a tree, construct the binary tree.
解题思路:
Given inorder and postorder traversal of a tree, construct the binary 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) { return buildTree(begin(inorder), end(inorder), begin(postorder), end(postorder)); } private: TreeNode *buildTree(vector<int>::iterator in_first, vector<int>::iterator in_last, vector<int>::iterator post_first, vector<int>::iterator post_last) { if (in_first == in_last) return nullptr; if (post_first == post_last) return nullptr; auto val = *prev(post_last); TreeNode *root = new TreeNode(val); auto in_root_pos = find(in_first, in_last, val); auto in_left_size = distance(in_first, in_root_pos); auto post_left_last = next(post_first, in_left_size); root->left = buildTree(in_first, in_root_pos, post_first, post_left_last); root->right = buildTree(next(in_root_pos), in_last, post_left_last, prev(post_last)); } };
相关文章推荐
- 如何选择真正适合你的存储平台
- 在Eclipse中搭建Struts框架过程详解
- Python学习笔记20151211
- 7.shell分支与循环结构
- select * into outfile权限错误问题的解决方法(Errcode:13)
- Javascript中改变this指针的指向的三种方法
- 深入理解SELinux SEAndroid(第一部分)
- LeetCode 232 Implement Queue using Stacks
- 《1024伐木累》-职位不分贵贱,没房子怎么乐
- 数值的整数次方
- 【转】SQL Server编程游标
- logback logback.xml 常用配置详解(转)
- linux下SSH远程连接服务慢解决方案
- CIFilter
- android混淆代码-proguard
- float类型在内存中的表示
- phalcon框架命名空间
- DTcms 导航选中样式以及简化方法
- 交换两个数的值(C语言)的两种方法
- (小知识点)将EditText的光标定位到字符的最后面