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

85 阅读1分钟

一 问题

二 代码

let buildTree = function(preorder, inorder) {
    //定义一个helper函数,以更方便的确定左右子树的起始位置
    let helper=function(prestart,preend,instart,inend){
        //如果数组不存在,返回null
        if(prestart>preend||instart>inend) return null;
        //前序遍历的第一个数字是根节点,因此首先获取根节点
        let value=preorder[prestart];
        //获取根节点在中序遍历数组中的位置,那么该位置左边的就是左子树,右边的是右子树
        let index=inorder.indexOf(value);
        //为了更好的递归剩下的左右子树,先计算一下左子树节点个数
        let countleft=index-instart;
        //创建根节点
        let root=new TreeNode(value);
        //注意参数为什么要这么传
        //prestart已经创建根节点了,所以prestart需要加一
        //第二个参数即加上左子树中节点的个数
        //第四个参数index用过了,因此index需要减一
        root.left=helper(prestart+1,prestart+countleft,instart,index-1);
        root.right=helper(prestart+countleft+1,preend,index+1,inend)
        //返回根节点
        return root;
    }
    return helper(0,preorder.length-1,0,inorder.length-1);
};