题目地址: 链接
思路: 通过前序遍历确定根节点,在中序遍历中找到根节点位置,分割左右子树。递归构建左子树和右子树,最终返回根节点。时间复杂度 O(n),空间复杂度 O(n)。
js
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number[]} preorder
* @param {number[]} inorder
* @return {TreeNode}
*/
var buildTree = function(preorder, inorder) {
let n = preorder.length;
if(n == 0) return null;
const inIdx = inorder.indexOf(preorder[0]);
const pre1 = preorder.slice(1, inIdx + 1);
const pre2 = preorder.slice(inIdx + 1);
const in1 = inorder.slice(0, inIdx);
const in2 = inorder.slice(inIdx + 1);
const left = buildTree(pre1, in1);
const right = buildTree(pre2, in2)
let root = new TreeNode(preorder[0], left, right);
return root;
};