已知前序遍历和中序遍历序列构造二叉树

题目

在这里插入图片描述

解法分析

IMG_20210516_212504.jpg
l推荐结合eetcode详解视频观看

根据解题分析的规律递归分治

我们用前序遍历的数组序列不断的进行递归分治
既然是递归分治,所以我们需要确定每一个分治情况下的范围,所以正好可以根据中序遍历得到范围。


class Solution {
public:
unordered_map<int,int>table;
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if(!preorder.size())
            return nullptr;
            //构建table
        for(int i=0;i<inorder.size();i++){
            table[inorder[i]] = i;
        }
        return buildTree(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
    }
private:
    TreeNode* buildTree(vector<int>&preorder,int preLeft,int preRight,
                        vector<int>&inorder, int inLeft,int inRight){
                        if(preLeft>preRight||inLeft>inRight)
                            return nullptr;
                        //获取当前根节点
                        TreeNode* root = new TreeNode(preorder[preLeft]);
                        //根据该根节点在中序遍历数组中的下标位置更新左右子树的范围
                        int pIndex = table[preorder[preLeft]];
                        root->left = buildTree(preorder,preLeft+1,preLeft-inLeft+pIndex,
                        inorder,inLeft,pIndex-1);
                        root->right = buildTree(preorder,preLeft-inLeft+pIndex+1,preRight,
                        inorder,pIndex+1,inRight);
                        return root;
    }
};

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值