题目描述:
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.
class Solution {
public:
TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
for(int i=0;i<post.size();i++) index[post[i]]=i;
return construct_tree(pre,post,0,pre.size()-1,0,post.size()-1);
}
TreeNode* construct_tree(vector<int>& pre, vector<int>& post, int a, int b, int c, int d)
{
if(a>b) return NULL;
if(a==b) return new TreeNode(pre[a]);
int root_val=pre[a];
int left_val=pre[a+1];
int left_length=index[left_val]-c+1; // 左子树的节点数
TreeNode* root=new TreeNode(root_val);
root->left=construct_tree(pre,post,a+1,a+left_length,c,c+left_length-1);
root->right=construct_tree(pre,post,a+left_length+1,b,c+left_length,d-1);
return root;
}
private:
unordered_map<int,int> index; // 存储后序遍历值和下标之间的关系
};