知序
返回
保存草稿
发布
H1
H2
H3
1
2
3
Excalidraw 图
AI 写作
AI 优化
目录
输入内容后显示目录
Markdown
# 38 - 从前序与中序遍历序列构造二叉树 ## 题目(LeetCode 105) 根据前序和中序遍历结果构造二叉树。 ## 解法:递归 + 哈希表 ```java class Solution { Map<Integer, Integer> indexMap = new HashMap<>(); public TreeNode buildTree(int[] preorder, int[] inorder) { for (int i = 0; i < inorder.length; i++) indexMap.put(inorder[i], i); return build(preorder, 0, preorder.length - 1, 0); } private TreeNode build(int[] preorder, int preL, int preR, int inL) { if (preL > preR) return null; TreeNode root = new TreeNode(preorder[preL]); int inRoot = indexMap.get(preorder[preL]); int leftSize = inRoot - inL; root.left = build(preorder, preL + 1, preL + leftSize, inL); root.right = build(preorder, preL + leftSize + 1, preR, inRoot + 1); return root; } } ``` ## 复杂度 - 时间 O(n),空间 O(n) ## 一句话总结 前序第一个是根,在中序中找到根的位置,左边是左子树右边是右子树,递归构建。 ## 说明 从前序和中序构造二叉树,递归 + 哈希表是最优解。哈希表将中序查找从 O(n) 降到 O(1),使总体时间复杂度为 O(n)。没有更优的替代方案。
预览
发布文章
添加摘要让读者更快了解文章内容
取消
确认发布
AI 写作助手
输入一个主题,AI 将为你生成一篇 Markdown 博客文章
AI 正在写作中...
取消
开始生成
AI 优化助手
描述你的修改需求,AI 将在原文基础上进行补充或微调
AI 正在优化中...
取消
开始优化
画布
从已有图里选
✕
图名
保存后生成 /images/excalidraw/<图名>.svg(只能用字母、数字、短横线、下划线、点)
取消
保存并插入