150強訪談中等

序列化與反序列化二元樹

「序列化和反序列化二元樹」問題的詳細指南和 Python 實作。

問題陳述

中等

序列化是將資料結構或物件轉換為位元序列的過程,以便可以將其儲存在檔案或記憶體緩衝區中,或透過網路連接鏈路進行傳輸,以便稍後在同一或另一個電腦環境中重建。

設計一個演算法來序列化和反序列化二元樹。對於序列化/反序列化演算法的工作方式沒有任何限制。您只需要確保二叉樹可以序列化為字串,並且該字串可以反序列化為原始樹結構。

該樹被表示為一個級別順序列表。實現兩個功能:

- serialize(root: list) -> str 將樹轉換為字串。

- deserialize(data: str) -> list 將字串轉換回樹。

為了進行測試,實作 serializeDeserialize(root: list) -> list 來序列化然後反序列化,傳回結果。

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

範例

Example 1
Input
[1,2,3,None,None,4,5]
Output
[1,2,3,None,None,4,5]
Explanation

The tree is serialized to a string and deserialized back to the same tree structure.

Example 2
Input
[]
Output
[]
Explanation

An empty tree serialized and deserialized remains 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 資源

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