↓快轉到主要內容
  1. LeetCode/

LeetCode 124: Binary Tree Maximum Path Sum

·1 分鐘· ·
LeetCode Hard Dynamic-Programming Tree Depth-First-Search Binary-Tree Dp-on-Trees
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: hard 第一次嘗試:2026-10-24

  • 提交紀錄:Wrong Answer ×4 → Accepted

解題思路
#

路徑可以在任何一個節點「轉彎」。用 DFS 回傳值(Tree 模板一):

  • dfs(node) 回傳「從 node 往下走一條鏈」的最大和。往上回傳只能選一邊,因為路徑不能分叉。
  • 在每個節點,用「左鏈 + 自己 + 右鏈」更新答案,這是在這裡轉彎的最大路徑。
  • 子鏈是負的就不要拿,當成 0:left = max(0, dfs(node.left))。

答案初始值要是 -inf,因為所有值都可能是負的。

我的嘗試
#

錯了四次才過,都是負數處理的問題:

  1. 沒有把負的鏈丟掉:[-2,-5] 回傳 -5,答案是 -2。根節點 -2 自己一個就是 -2,但更新答案時硬把左鏈 -5 加進去。
  2. 多加一個候選 node.val:[1,5,-3] 回傳 5,答案是 6(5 → 1)。更新答案時還是硬加兩邊(5 + 1 - 3 = 3),沒有考慮只拿左邊。
  3. 回傳值改成 max(left + val, right + val, val),但更新答案時還是加兩邊:[3,-4] 回傳 -1,答案是 3。第四次交了一模一樣的程式碼。
  4. 把左右鏈先用 max(0, ...) 截掉,才過。

正確解法
#

class Solution:
    def maxPathSum(self, root: Optional[TreeNode]) -> int:
        best = -inf

        def dfs(node):
            nonlocal best
            if not node:
                return 0
            left = max(0, dfs(node.left))
            right = max(0, dfs(node.right))
            best = max(best, left + right + node.val)
            return max(left, right) + node.val

        dfs(root)
        return best

左右鏈已經截成非負,回傳 max(left, right) + node.val 就夠了。

複雜度
#

時間 O(n),空間 O(h)。

要特別避免的錯誤
#

  • 往上回傳的是一條鏈(只能選一邊),更新答案的才是兩邊加起來。這兩個值不一樣。
  • 子鏈是負的要當成 0,不然會被迫拿進來。
  • 答案初始值用 -inf,不能用 0:全部是負數時答案是最大的那個負數。

面試口說整理
#

我用後序 DFS,每個節點回傳往下一條鏈的最大和,負的鏈直接當 0。在每個節點把左鏈、自己、右鏈加起來更新答案,這是在這個節點轉彎的最佳路徑;往上只回傳較大的一邊加自己,因為路徑不能分叉。答案從 -inf 開始,時間 O(n),空間 O(h)。

相關文章

LeetCode 1372: Longest ZigZag Path in a Binary Tree
·1 分鐘
LeetCode Medium Dynamic-Programming Tree Depth-First-Search Binary-Tree Dp-on-Trees
LeetCode 1372 解題筆記:每個節點回傳兩個值:從這裡先往左、先往右的最長 zigzag;往左走接的是左小孩「先往右」的值
LeetCode 687: Longest Univalue Path
·1 分鐘
LeetCode Medium Tree Depth-First-Search Binary-Tree Dp-on-Trees
LeetCode 687 解題筆記:DFS 回傳往下同值的最長鏈(邊數),在每個節點用左 + 右更新答案
LeetCode 2973: Find Number of Coins to Place in Tree Nodes
·2 分鐘
LeetCode Hard Dynamic-Programming Tree-Dp Depth-First-Search Sorting Heap Tree
LeetCode 2973 解題筆記:三個數的最大乘積只可能是「最大的三個」或「最小的兩個 × 最大的一個」;每個子樹只回傳最小 2 個和最大 3 個,後序合併
LeetCode 1373: Maximum Sum BST in Binary Tree
·1 分鐘
LeetCode Hard Dynamic-Programming Tree-Dp Binary-Search-Tree Depth-First-Search Tree
LeetCode 1373 解題筆記:後序遍歷回傳 (總和, 最小值, 最大值, 是不是 BST);左子樹的最大值 < 自己 < 右子樹的最小值才是 BST
LeetCode 337: House Robber III
·1 分鐘
LeetCode Medium Dynamic-Programming Tree Depth-First-Search Binary-Tree
LeetCode 337 解題筆記:樹上 DP,每個節點回傳(搶它、不搶它)的最大值;不是一層一層交錯搶
LeetCode 563: Binary Tree Tilt
·1 分鐘
LeetCode Easy Tree Depth-First-Search Binary-Tree Dp-on-Trees
LeetCode 563 解題筆記:後序回傳子樹的總和,每個節點的 tilt 是左右子樹總和的差,加進答案