DSA 部分中等

树木建造

“树构建”问题的详细指南和 Python 实现。

问题陈述

中等

编写一个函数 build_tree(preorder, inorder) ,根据其预序和中序遍历列表重建二叉树,并返回重建树的层序遍历(表示为列表,其中 None 表示空节点)。

约束条件
  • 1 <= len(preorder) <= 1000
  • inorder.length == preorder.length

示例

Example 1
Input
preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7]
Output
[3, 9, 20, None, None, 15, 7]
Explanation

Preorder allows identifying the root 3. Inorder splits left subtree [9] and right subtree [15, 20, 7]. Reconstructed tree has level order [3, 9, 20, None, None, 15, 7].

Need a Hint?
考虑使用树特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。