150强访谈中等

反转二叉树

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

问题陈述

中等

给定二叉树的根,反转树并返回其根。

反转二叉树意味着交换树中每个节点的左子节点和右子节点。

该树表示为一个级别顺序列表,其中 None 表示缺失节点。实现一个函数 invertTree(root: list) -> list ,它按级别顺序返回倒排树。

约束条件
  • The number of nodes in the tree is in the range [0, 100]
  • -100 <= Node.val <= 100

示例

Example 1
Input
[4,2,7,1,3,6,9]
Output
[4,7,2,9,6,3,1]
Explanation

The root stays 4. Its children swap: left becomes 7, right becomes 2. Their children also swap recursively.

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

The root stays 2. Left child 1 and right child 3 are swapped.

Example 3
Input
[]
Output
[]
Explanation

An empty tree inverted is still empty.

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

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