剑指Offer---JZ4 重建二叉树

描述
给定某二叉树的前序遍历和中序遍历,请重建出该二叉树并返回它的头结点。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建出如下图所示。
在这里插入图片描述

提示:
1.0 <= pre.length <= 2000
2.vin.length == pre.length
3.-10000 <= pre[i], vin[i] <= 10000
4.pre 和 vin 均无重复元素
5.vin出现的元素均出现在 pre里
6.只需要返回根结点,系统会自动输出整颗树做答案对比

示例1

输入: [1,2,4,7,3,5,6,8],[4,7,2,1,5,3,8,6]
返回值: {1,2,3,4,#,5,6,#,7,#,#,8}
说明: 返回根节点,系统会输出整颗二叉树对比结果

示例2

输入: [1],[1]
返回值: {1}

示例3

输入: [1,2,3,4,5,6,7],[3,2,4,1,6,5,7]
返回值: {1,2,5,3,4,6,7}

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function reConstructBinaryTree(pre, vin)
{
    // write code here
    if(!pre.length || !vin.length){
        return null;
    }
    const rootValue = pre[0];
    const node = new TreeNode(rootValue);
//     寻找中序二叉树中的根节点,此时可以把vin的左边为左子树,右边为右子树
    let i = 0;
    for(; i < vin.length; ++i){
        if(vin[i] === rootValue){
            break;
        }
    }
//     递归
    node.left = reConstructBinaryTree(pre.slice(1, i + 1), vin.slice(0, i));
    node.right = reConstructBinaryTree(pre.slice(i+1), vin.slice(i+1));
    return node;
}
module.exports = {
    reConstructBinaryTree : reConstructBinaryTree
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值