106.从中序与后序遍历构造二叉树
中序:左根右
后序:左右根
思路:
中序遍历需要定位根节点的坐标 前序和后序需要定位子树根节点的坐标
1.构造map方便通过root->value拿到该值在中序中的下标(in_root)
2.从后序的最后一个值拿到当前root的value
3.通过map拿到in_root
4.构造此时结点,分别赋值val,left, right(递归)
变量定义解释:
图中蓝色部分为左子树,粉色为右子树,红字为root
in_root为中序inorder中root的下标
in_left为中序树(子树)下标起点,in_right中序树(子树)下标终点,post_left,post_right同理
图解:
代码:
class Solution {
public:
unordered_map<int,int> in_map;
vector<int>postorder2;
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
//构造map方便拿in_root下标
for(int i=0;i<inorder.size();i++){
in_map[inorder[i]]=i;
}
postorder2=postorder;
TreeNode* root=buildTree(0,inorder.size()-1,0,postorder.size()-1);
return root;
}
TreeNode* buildTree(int in_left,int in_right,int post_left,int post_right) {
if(in_left>in_right || post_left>post_right)
return nullptr;
//后序拿到root
int root_val=postorder2[post_right];
//中序root下标
int in_root=in_map[root_val];
//创建结点
TreeNode* node=new TreeNode();
node->val=root_val;
//取值见图解
node->left=buildTree(in_left,in_root-1,post_left,post_left+in_root-in_left-1);
node->right=buildTree(in_root+1,in_right,post_left+in_root-in_left,post_right-1);
return node;
}
};