【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;
};
相关推荐
Hacker_Oldv3 小时前
数据驱动的测试优化:如何利用数据提高测试效率
自动化测试·软件测试·职场和发展
Promise4853 小时前
贝尔曼公式的迭代求解笔记
笔记·算法
程序员勋勋4 小时前
高频Robot Framework软件测试面试题
测试工具·职场和发展
福尔摩斯张4 小时前
Linux进程间通信(IPC)机制深度解析与实践指南
linux·运维·服务器·数据结构·c++·算法
你好~每一天4 小时前
未来3年,最值得拿下的5个AI证书!
数据结构·人工智能·算法·sqlite·hbase·散列表·模拟退火算法
杰克尼4 小时前
3. 分巧克力
java·数据结构·算法
zmzb01035 小时前
C++课后习题训练记录Day39
数据结构·c++·算法
Ayanami_Reii6 小时前
进阶数学算法-取石子游戏(ZJOI2009)
数学·算法·游戏·动态规划·区间dp·博弈论
一只小小汤圆6 小时前
已知圆弧的起点、终点、凸度 求圆弧的圆心
算法
丸码6 小时前
Java HashMap深度解析
算法·哈希算法·散列表