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

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

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

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

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

最近更新

  1. TCP协议是安全的吗?

    2024-04-12 23:10:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-12 23:10:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-12 23:10:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-12 23:10:03       18 阅读

热门阅读

  1. 基于springboot的车辆管理系统源码数据库

    2024-04-12 23:10:03       20 阅读
  2. vue3表格编辑(数据回显)和删除功能实现

    2024-04-12 23:10:03       19 阅读
  3. 【NC23803】DongDong认亲戚

    2024-04-12 23:10:03       54 阅读
  4. 【华为OD机试C++】蛇形矩阵

    2024-04-12 23:10:03       17 阅读
  5. 【算法刷题day24】回溯算法+简单剪枝

    2024-04-12 23:10:03       75 阅读
  6. 虚拟线程和普通线程

    2024-04-12 23:10:03       15 阅读
  7. 递归神经网络(Recursive Neural Networks)

    2024-04-12 23:10:03       16 阅读
  8. 题目 2011: 电导流的矩形

    2024-04-12 23:10:03       17 阅读