前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LeetCode热题100】【二叉树】从前序与中序遍历序列构造二叉树

【LeetCode热题100】【二叉树】从前序与中序遍历序列构造二叉树

作者头像
叶茂林
发布2024-04-12 08:32:47
660
发布2024-04-12 08:32:47
举报

题目链接:105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode)

前序遍历是根在前面,然后是左子树,再是右子树,中序遍历是左子树-根-右子树,通过前序遍历可以找到根,在中序遍历里面确定根的位置后可以知道左子树的长度和右子树的长度,如此可以在前序遍历中找到左子树和右子树的根,如此递归下去

为了更快的找到中序遍历里面根的位置,可以用哈希表存储下来根对应的索引

代码语言:javascript
复制
class Solution {
public:
    unordered_map<int, int> index;
    vector<int> preorder, inorder;

    TreeNode *build(int pre_left, int pre_right, int in_left, int in_right) {
        if (pre_left > pre_right)
            return nullptr;
        TreeNode *root = new TreeNode(preorder[pre_left]);
        int in_root = index[preorder[pre_left]];
        int left_size = in_root - in_left;
        root->left = build(pre_left + 1, pre_left + left_size, in_left, in_root - 1);
        root->right = build(pre_left + left_size + 1, pre_right, in_root + 1, in_root);
        return root;
    }

    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        this->preorder = preorder;
        this->inorder = inorder;
        for (int i = 0; i < inorder.size(); i++)
            index[inorder[i]] = i;
        return build(0, preorder.size() - 1, 0, inorder.size() - 1);
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-04-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档