题解 | #重建二叉树#
重建二叉树
https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
/*
* function TreeNode(x) {
* this.val = x;
* this.left = null;
* this.right = null;
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param preOrder int整型一维数组
* @param vinOrder int整型一维数组
* @return TreeNode类
*/
function reConstructBinaryTree( preOrder , vinOrder ) {
// write code here
if(preOrder.length === 0 || vinOrder.length === 0){
return null;
}
let root = new TreeNode(preOrder[0]);
let vinRootIndex = vinOrder.indexOf(preOrder[0]);
root.left = reConstructBinaryTree(preOrder.slice(1, vinRootIndex + 1), vinOrder.slice(0,vinRootIndex));
root.right = reConstructBinaryTree(preOrder.slice(vinRootIndex + 1, preOrder.length), vinOrder.slice(vinRootIndex + 1, vinOrder.length));
return root;
}
module.exports = {
reConstructBinaryTree : reConstructBinaryTree
};

查看29道真题和解析