javascript 先序遍历和中序遍历生成二叉树

245 阅读1分钟

剑指offer上的一道算法题,用js实现:

function TreeNode(x) {                             //构建节点
  this.val = x;
  this.left = null;
  this.right = null;
}

function reConstructBinaryTree(pre, vin){     
    //var a='';a.length=0;切割无元素时长度为0
    if(pre.length===0){
        return null
    }
    var root =new TreeNode(pre[0]);//根节点
    //依据中序遍历左右子树分别在根节点的特点,切割生成左右子树
    var lt=vin.slice(0,vin.indexOf(pre[0]));
    var rt=vin.slice(vin.indexOf(pre[0])+1)
    //递归生成左右子树
    root.left=reConstructBinaryTree(pre.slice(1,1+lt.length),lt);
    root.right=reConstructBinaryTree(pre.slice(pre.length-rt.length),rt);
    return root
    
}