【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;
};
相关推荐
吃着火锅x唱着歌4 小时前
LeetCode 2389.和有限的最长子序列
算法·leetcode·职场和发展
嶔某4 小时前
二叉树的前中后序遍历(迭代)
算法
007php0074 小时前
百度面试题解析:微服务架构、Dubbo、Redis及其一致性问题(一)
redis·百度·docker·微服务·容器·职场和发展·架构
WWZZ20254 小时前
快速上手大模型:机器学习2(一元线性回归、代价函数、梯度下降法)
人工智能·算法·机器学习·计算机视觉·机器人·大模型·slam
孤狼灬笑5 小时前
深度学习经典分类(算法分析与案例)
rnn·深度学习·算法·cnn·生成模型·fnn
dragoooon345 小时前
[优选算法专题四.前缀和——NO.26二维前缀和]
算法
苏小瀚6 小时前
算法---位运算
java·算法
Code小翊6 小时前
归并排序基础理解
数据结构·算法·排序算法
2401_841495646 小时前
【数据结构】基于Floyd算法的最短路径求解
java·数据结构·c++·python·算法··floyd