题解 | 重建二叉树

重建二叉树

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

前序遍历判断根节点,中序遍历判断左右

[1,2,4,7,3,5,6,8],[4,7,2,1,5,3,8,6]

根节点为 1, 中序遍历判断位置,对数组进行左右切分 [4,7,2][5,3,8,6],前序遍历同样切分 [2,4,7] [3,5,6,8]

1、左子树:[2,4,7] [4,7,2]

前序遍历第一个2 就为 root 的左节点,然后已 2 再为根节点重复上述操作:

中序遍历切分:[4,7] [] 前端遍历切分:[4,7][] ,重复执行....

2、右子树:[3,5,6,8] [5,3,8,6]同样直接上述操作:

前序遍历第一个 3 就为 root 的右节点 , 重复执行....

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param preOrder int整型一维数组
 * @param vinOrder int整型一维数组
 * @return TreeNode类
 */
function reConstructBinaryTree(preOrder, vinOrder) {
    console.log("-----");
    console.log(preOrder, vinOrder);
    if (!preOrder.length || !vinOrder.length) return null;
    // write code here
    const root = new TreeNode(preOrder[0]);
    const midIndex = vinOrder.indexOf(preOrder[0]);
    root.left = reConstructBinaryTree(
        preOrder.slice(1, midIndex + 1),
        vinOrder.slice(0, midIndex)
    );
    root.right = reConstructBinaryTree(
        preOrder.slice(midIndex + 1),
        vinOrder.slice(midIndex + 1)
    );
    return root;
}
module.exports = {
    reConstructBinaryTree: reConstructBinaryTree,
};

全部评论

相关推荐

积极的小学生不要香菜:你才沟通多少,没500不要说难
点赞 评论 收藏
分享
06-07 17:17
嘉兴学院 教师
心爱的idea:你孩
点赞 评论 收藏
分享
07-24 12:30
湘潭大学 营销
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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