71:Construct Binary Tree from Preorder and Inorder Traversal
来源:互联网 发布:tmplate可以写js 编辑:程序博客网 时间:2024/05/29 14:36
题目:Given preorder and inorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
下面解法代码的思想及编写参考了网址https://github.com/soulmachine/leetcode#leetcode题解题目
代码如下:
// 递归,时间复杂度 O(n),空间复杂度 O(log n)class Solution {public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { return buildTree(begin(preorder), end(preorder), begin(inorder), end(inorder)); } template <class InputIterator> TreeNode* buildTree(InputIterator pre_first, InputIterator pre_last, InputIterator in_first, InputIterator in_last) { if (pre_first == pre_last) return nullptr; if (in_first == in_last) return nullptr; auto root = new TreeNode(*pre_first); auto inRootPos = find(in_first, in_last, *pre_first) auto leftSize = distance(in_first, inRootPos); auto pre_left_last = next(pre_first, leftSize + 1); root -> left = buildTree(next(pre_first), pre_left_last, in_first, inRootPos); root -> right = buildTree(pre_left_last, pre_last, next(inRootPos), in_last); return root; }};
0 0
- 71:Construct Binary Tree from Preorder and Inorder Traversal
- *(leetcode) Construct Binary Tree from Preorder and Inorder Traversal (tree)
- LeetCode[Tree]: Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode][tree] Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal & Construct Binary Tree from Inorder and P
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Construct Binary Tree from Preorder and Inorder Traversal
- [Leetcode] Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode: Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Construct Binary Tree from Preorder and Inorder Traversal
- leetcode 109: Construct Binary Tree from Preorder and Inorder Traversal
- 【leetcode】Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- b-tree、b+-tree、2-3-4树个人总结
- Oracle 高级查询
- Vue-组件props属性再回顾
- POJ 1753一道状态压缩题。
- seleniumWebDriver的API操作杀进程、截屏、执行js脚本_10_4
- 71:Construct Binary Tree from Preorder and Inorder Traversal
- RxAndroid学习之旅
- 微信公众平台开发-access_token获取及应用(含源码)
- 简单选择排序
- 【Logistic回归】原理及Python代码示例
- JavaScricp简介
- spring data 接口之 CrudRepository
- MySQL数据库调优技巧
- Codeforces 782C Andryusha and Colored Balloons(BFS)