题解 | #重建二叉树#
重建二叉树
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) return null;
let root = new TreeNode(preOrder[0]);
console.log(root);
let temp = vinOrder.indexOf(root.val);
// console.log('temp:',temp);
root.left = reConstructBinaryTree(
preOrder.slice(1, temp + 1),
vinOrder.slice(0, temp)
);
root.right = reConstructBinaryTree(
preOrder.slice(temp + 1),
vinOrder.slice(temp + 1)
);
return root;
}
let root = reConstructBinaryTree([2], [2]);
console.log(root);
module.exports = {
reConstructBinaryTree: reConstructBinaryTree,
};
查看25道真题和解析
腾讯成长空间 5950人发布