[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
原创粉丝点击