【算法】leetcode 105 从前序与中序遍历序列构造二叉树

题目

输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。

假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

示例 1:

复制代码
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]

示例 2:

复制代码
Input: preorder = [-1], inorder = [-1]
Output: [-1]

限制:

0 <= 节点个数 <= 5000

解答

cpp 复制代码
#include <iostream>
#include <unordered_map>
#include <vector>

using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
       for (int i = 0; i < inorder.size(); i++)
        {
            // 用中序遍历数组建立 值-下标 的映射
            value_index[inorder[i]] = i;
        }
        return recursive(preorder,0, 0, inorder.size() - 1);
    }
    TreeNode *recursive(vector<int>& pre,int pre_root, int in_left, int in_right)
    {
        if (in_left > in_right) return nullptr;
        // 将对应的 val 赋给 node 节点
        TreeNode *node = new TreeNode(pre[pre_root]);
        int in_root = value_index[pre[pre_root]];
        node->left = recursive(pre,pre_root + 1, in_left, in_root - 1);
        node->right = recursive(pre,pre_root + in_root - in_left + 1, in_root + 1, in_right);
        return node;
    }
private:
    unordered_map<int, int> value_index;
};
相关推荐
星恒随风7 分钟前
C++ STL 详解:set 与 multiset 的使用、区间查询和算法应用
开发语言·c++·笔记·学习·算法
Lumos18615 分钟前
《ESP32 物联网全栈实战-02》ESP-IDF 工程结构
算法
QN1幻化引擎25 分钟前
把 意识评测做成了一场"非侵入实验":不碰生产代码,分数反而更真了
人工智能·算法·架构
冻柠檬飞冰走茶1 小时前
PTA基础编程题目集 7-17 爬动的蠕虫(C语言实现)
c语言·开发语言·数据结构·算法
会编程的土豆2 小时前
LeetCode 热题 HOT100(一):哈希表与双指针入门(Go 实现)
算法·leetcode·职场和发展
学习中.........2 小时前
并行 BPE 训练 与 手写 `Tokenizer`
人工智能·算法·机器学习·语言模型
科学实验家2 小时前
动态规划2
算法·动态规划
東隅已逝,桑榆非晚2 小时前
数据结构常见英文术语速查手册
数据结构
imuliuliang11 小时前
关于数据结构在算法设计中的核心作用解析7
算法
2401_8949155313 小时前
GEO 搜索优化完整源码从零部署:环境配置、集群搭建全流程
开发语言·python·tcp/ip·算法·unity