一、题目地址
二、思路地址
https://www.bilibili.com/video/BV1LJ411y7Xa?from=search&seid=8914552986488165078
二、具体代码
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function reConstructBinaryTree(pre, vin)
{
if(!pre.length || !vin.length) {
return null;
}
// 1、获取到树的根节点的value值
let root = new TreeNode(pre[0]);
// 2、构建left左子树, right右子树
// 2.1、找到根节点的index值
let rValue = root.val;
let index = vin.indexOf(rValue);
// 2.2、root.left = reConstructBinaryTree(左子树的前序遍历, 左子树的中序遍历);
let leftPre = pre.slice(1, index + 1);
let leftVin = vin.slice(0, index);
root.left = reConstructBinaryTree(leftPre, leftVin);
// 2.3、root.right = reConstructBinaryTree(右子树的前序遍历, 右子树的中序遍历);
let rightPre = pre.slice(index + 1);
let rightVin = vin.slice(index + 1);
root.right = reConstructBinaryTree(rightPre, rightVin);
// 3、返回重建好的二叉树
return root;
}
module.exports = {
reConstructBinaryTree : reConstructBinaryTree
};