150強訪談

二元樹的最大深度

「二元樹最大深度」問題的詳細指南和 Python 實作。

問題陳述

給定二元樹的根,返回其最大深度。

二元樹的最大深度是從根節點到最遠葉節點的最長路徑上的節點數。

該樹表示為一個層級順序列表,其中 None 表示缺失節點。實作函數 maxDepth(root: list) -> int

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

範例

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

The tree has 3 levels: root [3], second level [9,20], third level [15,7]. The longest path is 3->20->15 or 3->20->7, both of depth 3.

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

The tree has root 1 with only a right child 2. Depth is 2.

Example 3
Input
[]
Output
0
Explanation

An empty tree has depth 0.

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

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