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

46 阅读1分钟

leetcode-105.png

根据前序遍历、中序遍历来生成树,这里的要求就是要懂,前中后序的遍历过程了
前序:根左右
中序:左根右
后序:左右根
有了这个结论之后,可以得出,可以先根据前序来找到根节点,然后在中序遍历里面找到根节点的索引,讲中序遍历分成两半。

var buildTree = function (preorder, inorder) {
    if (preorder.length === 0 && inorder.length === 0) return null
    let node = preorder[0]
    let index = inorder.indexOf(node)
    let root = new TreeNode(node)
    root.left = buildTree(preorder.slice(1, index + 1), inorder.slice(0, index))
    root.right = buildTree(preorder.slice(index + 1), inorder.slice(index + 1))
    return root
};Ï