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

题目地址: 链接

思路: 通过前序遍历确定根节点,在中序遍历中找到根节点位置,分割左右子树。递归构建左子树和右子树,最终返回根节点。时间复杂度 O(n),空间复杂度 O(n)。

js 复制代码
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */
var buildTree = function(preorder, inorder) {
    let n = preorder.length;
    if(n == 0) return null;

    const inIdx = inorder.indexOf(preorder[0]);
    const pre1 = preorder.slice(1, inIdx + 1);
    const pre2 = preorder.slice(inIdx + 1);
    

    const in1 = inorder.slice(0, inIdx);
    const in2 = inorder.slice(inIdx + 1);
    
    const left = buildTree(pre1, in1);
    const right = buildTree(pre2, in2)
    let root = new TreeNode(preorder[0], left, right);
    return root;
};
相关推荐
YYuCChi几秒前
代码随想录算法训练营第三十四天 | 62.不同路径、63.不同路径||
算法
小明同学014 分钟前
[C++进阶] 深度解析AVLTree
c++·算法·visualstudio
CoderCodingNo11 分钟前
【GESP】C++五级练习题 luogu-P1031 [NOIP 2002 提高组] 均分纸牌
开发语言·c++·算法
梯度下降中1 小时前
求职面试中的线代知识总结
人工智能·线性代数·算法·机器学习
七禾页丫1 小时前
面试记录14 上位机软件工程师
面试·职场和发展
SmartBrain1 小时前
OCR 模型在医疗场景的选型研究
人工智能·算法·语言模型·架构·aigc·ocr
梵刹古音1 小时前
【C语言】 跳转语句
c语言·开发语言·算法
liu****2 小时前
29.路径类dp
c++·算法·acm
JMchen1232 小时前
Android计算摄影实战:多帧合成、HDR+与夜景算法深度剖析
android·经验分享·数码相机·算法·移动开发·android-studio
阿猿收手吧!2 小时前
【C++】C++模板特化:精准定制泛型逻辑
开发语言·c++·算法