150強訪談

二元樹最大路徑和

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

問題陳述

二元樹中的路徑是節點序列,其中序列中的每對相鄰節點都有一條連接它們的邊。一個節點最多只能在序列中出現一次。請注意,該路徑不需要經過根。

路徑的路徑和是路徑中節點值的總和。

給定二元樹的根,返回任何非空路徑的最大路徑和。

該樹被表示為一個級別順序列表。實作函數 maxPathSum(root: list) -> int

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

範例

Example 1
Input
[1,2,3]
Output
6
Explanation

The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.

Example 2
Input
[-10,9,20,None,None,15,7]
Output
42
Explanation

The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.

Example 3
Input
[-3]
Output
-3
Explanation

The only path is the single node -3.

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

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