解题思路:
构建一个二叉树需要构建三部分:root、左子树、右子树
左子树、右子树的构建,又包括:root、左子树、右子树
解题关键在于定位出根节点,划分出左右子树,然后 递归 构建左右子树
解题参考:https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solution/ding-wei-chu-gen-jie-dian-de-wei-zhi-hua-fen-zuo-y/
var buildTree = function(preorder, inorder) {
// 递归出口: 前序数组中的元素被用完了
if(preorder.length === 0) return null;
// 前序遍历的第一个元素为根元素
const tem = preorder[0];
// 创建一个二叉树
let root = new TreeNode(tem);
// 获取根元素在中序遍历中的位置下标index, 则以该根元素可以进行切割左右子树:左子树为inorder.slice(0, index), 右子树为inorder.slice(index+1);
// 前序遍历中左右子树进行切割的依据是:左子树的长度根据中序遍历左子树的长度(长度index)来决定,所以前序遍历的左子树为preorder.slice(1, 1 + index), 右子树长度为preoder.slice(1+index)
let index = inorder.indexOf(tem); // 即是根节点的下标,同时也是左子树的长度
// 递归构建树左子节点:左子树的前序数组,左子树的中序数组
root.left = buildTree(preorder.slice(1, 1 + index), inorder.slice(0, index));
// 递归构建树右子节点:右子树的前序数组,右子树的中序数组
root.right = buildTree(preorder.slice(1+index), inorder.slice(index+1));
return root;
};