DSA 部分中等

可折疊樹

“可折疊樹”問題的詳細指南和 Python 實作。

問題陳述

中等

寫一個函數 is_foldable(tree_arr) ,它採用二元樹 tree_arr 的陣列表示形式,並檢查該樹是否可折疊。如果一棵樹的左子樹和右子樹是彼此的結構鏡像(值並不重要,只有結構),那麼該樹是可折疊的。

約束條件
  • 0 <= len(tree_arr) <= 1000

範例

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

Left child has right child 4. Right child has left child 5. Structures are symmetric mirrors.

Example 2
Input
tree_arr = [1, 2, 3, 4, None, 5, None]
Output
False
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 資源

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