题解 | #重建二叉树#

重建二叉树

https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function reConstructBinaryTree(pre, vin)
{
    // write code here
    if (pre.length ===0) return null
    const rootValue = pre[0]
    const vinRootIndex = vin.indexOf(rootValue)
    const leftVin = vin.slice(0, vinRootIndex)
    const rightVin = vin.slice(vinRootIndex + 1)
    const leftPre = pre.slice(1, leftVin.length + 1)
    const rightPre = pre.slice(leftVin.length + 1)
    const root = new TreeNode(rootValue)
    root.left = reConstructBinaryTree(leftPre, leftVin)
    root.right = reConstructBinaryTree(rightPre, rightVin)
    return root
}

module.exports = {
    reConstructBinaryTree : reConstructBinaryTree
};

全部评论

相关推荐

08-06 08:33
四川大学 Java
OPPO官方内推:卧槽!!!啥破公司啊!!!
投递OPPO等公司10个岗位
点赞 评论 收藏
分享
做个有文化的流氓:Offer收割机
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务