【LeetCode】105. 从前序与中序遍历序列构造二叉树

作者:小卢

专栏:《Leetcode》

喜欢的话:世间因为少年的挺身而出,而更加瑰丽。 ------《人民日报》


105. 从前序与中序遍历序列构造二叉树

力扣

题目描述:

给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

示例:

思路:

利用previ去变量前序数组找到根的位置,然后再去中序数组里面找到根,分割左右子树区间

然后begin和end在中序数组去分割左右子树,然后利用递归构建树

代码:

cpp 复制代码
class Solution {
public:
    TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder,int&previ,int begin,int end) {
        if(begin>end)
        return nullptr;
        TreeNode*root=new TreeNode(preorder[previ]);
        int rooti=0;
        while(preorder[previ]!=inorder[rooti])
        {
            rooti++;
        }
        previ++;
        root->left=_buildTree(preorder,inorder,previ,begin,rooti-1);
        root->right=_buildTree(preorder,inorder,previ,rooti+1,end);
        return root;
}
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int i=0;
        return _buildTree(preorder,inorder,i,0,inorder.size()-1);
    }

};
相关推荐
kobesdu14 分钟前
FAST-LIO2 + 蓝海M300激光雷达:从建图到实时栅格图的完整流程
算法·机器人·ros·slam·fast lio
x_xbx14 分钟前
LeetCode:438. 找到字符串中所有字母异位词
算法·leetcode·职场和发展
MThinker14 分钟前
K230+canMV+micropython实现低成本MLX90640红外热成像测温模块(续)
算法·智能硬件·micropython·canmv·k230
小菜鸡桃蛋狗18 分钟前
C++——string(下)
算法
学习永无止境@21 分钟前
灰度图像中值滤波算法实现
图像处理·算法·计算机视觉
ysa05103026 分钟前
斐波那契上斐波那契【矩阵快速幂】
数据结构·c++·笔记·算法
CHANG_THE_WORLD40 分钟前
模拟解析:宽度数组 `[1,2,1]`,10个条目的 XRef 流
java·前端·算法
lixinnnn.44 分钟前
多源BFS:矩阵距离
算法·宽度优先
CHANG_THE_WORLD1 小时前
PDFium 处理通用 `W` 数组的方式
数据结构·算法
派大星~课堂1 小时前
【力扣-94.二叉树的中序遍历】Python笔记
笔记·python·leetcode