106.从中序与后序遍历构造二叉树

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;
    }

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值