题解 | #重建二叉树#
重建二叉树
https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function reConstructBinaryTree(pre, vin)
{
// write code here
if (pre.length ===0) return null
const rootValue = pre[0]
const vinRootIndex = vin.indexOf(rootValue)
const leftVin = vin.slice(0, vinRootIndex)
const rightVin = vin.slice(vinRootIndex + 1)
const leftPre = pre.slice(1, leftVin.length + 1)
const rightPre = pre.slice(leftVin.length + 1)
const root = new TreeNode(rootValue)
root.left = reConstructBinaryTree(leftPre, leftVin)
root.right = reConstructBinaryTree(rightPre, rightVin)
return root
}
module.exports = {
reConstructBinaryTree : reConstructBinaryTree
};

