150強訪談中等

二元樹層次順序遍歷

「二元樹層級順序遍歷」問題的詳細指南和 Python 實作。

問題陳述

中等

給定二元樹的根,傳回其節點值的層序遍歷。 (即由左至右,逐級)。

該樹被表示為一個級別順序列表。實作一個函數 levelOrder(root: list) -> list 傳回一個列表列表,其中每個內部列表都包含該等級的值。

約束條件
  • The number of nodes in the tree is in the range [0, 2000]
  • -1000 <= Node.val <= 1000

範例

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

Level 0: [3]. Level 1: [9,20]. Level 2: [15,7].

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

Only one node at level 0.

Example 3
Input
[]
Output
[]
Explanation

Empty tree has no levels.

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

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