题解 | #重建二叉树#
重建二叉树
https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
// function TreeNode(x) { // this.val = x; // this.left = null; // this.right = null; // } function reConstructBinaryTree(pre, vin) { if (!pre.length || !vin.length) { return null; } // shift用于把数组中第一个元素删除,并返回其元素值 const root = new TreeNode(pre.shift()); const index = vin.indexOf(root.val); //方法可提取字符串或数组的某个部分,并以新的字符串或数组返回被提取的部分。 //slice(start,end) 包含start,不包含end,提取了左子树 root.left = reConstructBinaryTree(pre, vin.slice(0, index)); //slice(start) 从start开始到数组结尾,提取到右子树 root.right = reConstructBinaryTree(pre, vin.slice(index + 1)); return root; } module.exports = { reConstructBinaryTree: reConstructBinaryTree, };