【算法】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;
};
相关推荐
xu_yule14 小时前
算法基础(数论)—费马小定理
c++·算法·裴蜀定理·欧拉定理·费马小定理·同余方程·扩展欧几里得定理
girl-072615 小时前
2025.12.28代码分析总结
算法
NAGNIP18 小时前
GPT-5.1 发布:更聪明,也更有温度的 AI
人工智能·算法
NAGNIP18 小时前
激活函数有什么用?有哪些常用的激活函数?
人工智能·算法
元亓亓亓19 小时前
LeetCode热题100--416. 分割等和子集--中等
算法·leetcode·职场和发展
BanyeBirth19 小时前
C++差分数组(二维)
开发语言·c++·算法
xu_yule20 小时前
算法基础(数论)—算法基本定理
c++·算法·算数基本定理
CoderCodingNo21 小时前
【GESP】C++五级真题(结构体排序考点) luogu-B3968 [GESP202403 五级] 成绩排序
开发语言·c++·算法
浅川.2521 小时前
STL专项:stack 栈
数据结构·stl·stack