150强访谈中等

构造二叉树

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

问题陈述

中等

给定两个整数数组 preorder 和 inorder,其中 preorder 是二叉树的前序遍历,inorder 是同一棵树的中序遍历,构造并返回二叉树。

该树应作为级别顺序列表返回。实现函数 buildTree(preorder: list, inorder: list) -> list

约束条件
  • 1 <= preorder.length <= 3000
  • inorder.length == preorder.length
  • -3000 <= preorder[i], inorder[i] <= 3000
  • preorder and inorder consist of unique values
  • Each value of inorder also appears in preorder
  • preorder is guaranteed to be the preorder traversal of the tree
  • inorder is guaranteed to be the inorder traversal of the tree

示例

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

Preorder: root is 3. In inorder, 9 is to the left of 3 (left subtree) and [15,20,7] is to the right (right subtree). Recursively build: left subtree is just [9], right subtree has root 20 with children 15 and 7.

Example 2
Input
[-1], [-1]
Output
[-1]
Explanation

Single node tree.

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 资源

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