LeetCode 105 从前序与中序遍历序列构造二叉树

93 阅读1分钟

题目描述:给定一棵树的前序遍历 preorder 与中序遍历  inorder。请构造二叉树并返回其根节点。

image.png image.png

var buildTree = function(preorder, inorder) {
    if(!preorder.length || !inorder.length) return null


    const root = new TreeNode(preorder[0])

    const index = inorder.indexOf(preorder[0])

    root.left = buildTree(preorder.slice(1,index+1), inorder.slice(0,index))
    
    root.right = buildTree(preorder.slice(index+1,preorder.length), inorder.slice(index+1, inorder.length))

    return root
};