[Leetcode]Construct Binary Tree from Inorder and Postorder Traversal
来源:互联网 发布:springmvc国际化对js 编辑:程序博客网 时间:2024/06/10 20:04
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree
这道题要根据中序和后序的便利结果构建一棵树出来。
理解以下性质,这道题思路就没问题了:
1、后序遍历的最后一个元素就是树的根节点。
2、在中序遍历中找到根节点,会将树分为左右子树两部分,假设左子树有a个元素,右子树有b个元素。
3、后序遍历中和中序遍历一样分为左右子树两部分,左子树下标为0~a-1,右子树下标为a~a+b-2(最后一个元素是根节点,一定要注意去掉)。
4、创建根节点,左右子树分别迭代求解
class Solution {public:TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {return build(inorder, inorder.begin(), inorder.end(), postorder, postorder.begin(), postorder.end());}TreeNode *build(vector<int> &inorder, vector<int>::iterator iBegin, vector<int>::iterator iEnd,vector<int> &postorder, vector<int>::iterator pBegin, vector<int>::iterator pEnd){if (iBegin == iEnd) return NULL;vector<int>::iterator rootIte = find(iBegin, iEnd, *(pEnd - 1));TreeNode *root = new TreeNode(*rootIte);root->left = build(inorder, iBegin, rootIte, postorder, pBegin, pBegin + (rootIte - iBegin));root->right = build(inorder, rootIte + 1, iEnd, postorder, pBegin + (rootIte - iBegin), pEnd - 1);return root;}};
这道题用find方法去寻找根节点,find方法返回迭代器,所以索性这道题全部用迭代器来解决,最后代码还挺简洁,只有十几行,比用下标简洁了不少,由此可见STL的泛型算法还是好东西~~~
0 0
- *(leetcode) Construct Binary Tree from Inorder and Postorder Traversal (tree)
- LeetCode[Tree]: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- [Leetcode] Construct Binary Tree from Inorder and Postorder Traversal
- leetcode 110: Construct Binary Tree from Inorder and Postorder Traversal
- 【leetcode】Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode-Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode - Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- 苹果mac电脑中brew的安装使用及卸载详细教程
- 随机数算法
- Win32控制台应用程序如何更换图标
- Activity的状态保存
- Git基本概念
- [Leetcode]Construct Binary Tree from Inorder and Postorder Traversal
- Mac下使用eclipse问题
- path的使用
- SKIP_BODY,SKIP_PAGE,EVAL_BODY_INCLUDE,EVAL_BODY_AGAIN
- 排序算法之冒泡排序 C++和PHP实现
- make: warning: Clock skew detected. Your build may be incomplete.
- ppt转换成pdf转换器怎么使用
- HDU 2553 N皇后问题 (回溯法 递归·非递归)
- 使用标准库函数中的printf