题解 | #重建二叉树#
重建二叉树
http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function reConstructBinaryTree(pre, vin)
{
//若先序数组为空 则为null(递归中止)
if(pre[0]==undefined){
return null
}
//将先序的第一个元素作为root
const node = new TreeNode(pre[0])
let vi =vin.indexOf(pre[0])
//以该元素为定位 切分中序数组为左右中序数组
const vleft = vin.slice(0,vi)
const vright = vin.slice(vi+1,vin.length)
//同理将先序数组切分
const pleft = pre.slice(1,vleft.length+1)
const pright = pre.slice(vleft.length+1)
//递归构建树
node.left = reConstructBinaryTree(pleft,vleft)
node.right = reConstructBinaryTree(pright,vright)
return node
}
module.exports = {
reConstructBinaryTree : reConstructBinaryTree
};

