889. Construct Binary Tree from Preorder and Postorder Traversal**
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/
题目描述
Return any binary tree that matches the given preorder and postorder traversals.
Values in the traversals pre
and post
are distinct positive integers.
Example 1:
Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]
Note:
1 <= pre.length == post.length <= 30
pre[]
andpost[]
are both permutations of1, 2, ..., pre.length
.- It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.
C++ 实现 1
注意前序遍历和和后序遍历得到的数组的特点.
![](https://i-blog.csdnimg.cn/blog_migrate/67cf5ff2997cdc66e88578518424e67f.jpeg)
之后递归求解即可. 迭代的解法尚待研究. 类似的题是 889. Construct Binary Tree from Preorder and Postorder Traversal**.
class Solution {
public:
TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
if (pre.empty()) return nullptr;
if (pre.size() == 1) return new TreeNode(pre[0]);
TreeNode *root = new TreeNode(pre[0]);
int n = pre.size(), val = post[n - 2];
auto it = std::find(pre.begin(), pre.end(), val);
vector<int> l_pre(pre.begin() + 1, it),
l_post(post.begin(), post.begin() + l_pre.size());
vector<int> r_pre(it, pre.end()),
r_post(post.begin() + l_pre.size(), post.end() - 1);
auto ltree = constructFromPrePost(l_pre, l_post);
auto rtree = constructFromPrePost(r_pre, r_post);
root->left = ltree;
root->right = rtree;
return root;
}
};