【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;
};
相关推荐
Insight3 分钟前
拒绝手动 Copy!一文吃透 PyTorch/NumPy 中的广播机制 (Broadcasting)
算法
CoovallyAIHub24 分钟前
工业视觉检测:多模态大模型的诱惑
深度学习·算法·计算机视觉
Jayden_Ruan31 分钟前
C++分解质因数
数据结构·c++·算法
bubiyoushang8881 小时前
MATLAB实现雷达恒虚警检测
数据结构·算法·matlab
wu_asia1 小时前
编程技巧:如何高效输出特定倍数数列
c语言·数据结构·算法
AlenTech1 小时前
207. 课程表 - 力扣(LeetCode)
算法·leetcode·职场和发展
练习时长一年2 小时前
LeetCode热题100(杨辉三角)
算法·leetcode·职场和发展
lzllzz232 小时前
bellman_ford算法
算法
栈与堆2 小时前
LeetCode 19 - 删除链表的倒数第N个节点
java·开发语言·数据结构·python·算法·leetcode·链表
sunfove2 小时前
麦克斯韦方程组 (Maxwell‘s Equations) 的完整推导
线性代数·算法·矩阵