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

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。