Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/**
* Definition for binary tree
* 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 build(begin(inorder), end(inorder), begin(postorder), end(postorder));
}
template<typename InputIter>
TreeNode *build(InputIter in_first, InputIter in_last, InputIter post_first, InputIter post_last) {
if (post_first == post_last) return NULL;
if (in_first == in_last) return NULL;
auto root = new TreeNode(*prev(post_last));
auto inRootPos = find(in_first, in_last, *prev(post_last));
auto leftSize = distance(in_first, inRootPos);
root->left = build(in_first, next(in_first, leftSize), post_first, next(post_first, leftSize));
root->right = build(next(inRootPos), in_last, next(post_first, leftSize), prev(post_last));
return root;
}
};
本文介绍了一种通过给定的中序遍历和后序遍历序列来构建二叉树的方法。该方法假设树中不存在重复元素,并提供了一个C++实现方案。

被折叠的 条评论
为什么被折叠?



