题解 | #重建二叉树#
重建二叉树
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 || !vin.length){ return null } let root = pre[0] let tnode = new TreeNode(root) let index = vin.indexOf(root) tnode.left = reConstructBinaryTree(pre.slice(1,index+1),vin.slice(0,index)) tnode.right = reConstructBinaryTree(pre.slice(index+1),vin.slice(index+1)) return tnode } module.exports = { reConstructBinaryTree : reConstructBinaryTree };