105. 从前序与中序遍历序列构造二叉树
「题目:」
给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。
「示例:」
输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7],输出: [3,9,20,null,null,15,7]。
「解题思路:」
由于二叉树是递归定义的,所以只需要寻找根节点、左子树以及右子树之间的关系,即可构造出二叉树。
参照上述图解,通过前序序列可以轻松地找到当前子树的根节点,然后通过中序序列依据该根节点分割其左右子树,所以这里有一个重要的隐藏条件就是二叉树中的元素值不能重复!
时间复杂度:O(n),空间复杂度:O(n)。
const buildTree = (preorder, inorder) => {
// 递归中止条件
if (preorder.length === 0) {
return null;
}
const rootElement = preorder[0];
const root = new TreeNode(rootElement);
const rootElementIndex = inorder.indexOf(rootElement);
root.left = buildTree(preorder.slice(1, rootElementIndex + 1), inorder.slice(0, rootElementIndex));
root.right = buildTree(preorder.slice(rootElementIndex + 1), inorder.slice(rootElementIndex + 1));
return root;
}
针对上述解法中的 indexOf 耗时,可以通过空间换时间的技巧来优化。
利用哈希表将中序序列中各个根节点的映射关系提前保存好,但是这样会面临一个新的问题?就是不能再对 inorder 进行 slice,这样会导致映射关系发生变化。这里就需要转化为利用下标来维护两个