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