Binary Tree Maximum Path Sum 解題教學:3 種解法完整比較|LeetCode 124 Best Practice

Binary Tree Maximum Path Sum 解題教學示意圖|LeetCode 124

本文完整拆解 LeetCode 124 Binary Tree Maximum Path Sum 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Binary Tree Maximum Path Sum 一次弄懂。

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node’s values in the path.

Given the root of a binary tree, return the maximum path sum of any non-empty path.

 

Example 1:

Input: root = [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: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.

 

Constraints:

  • The number of nodes in the tree is in the range [1, 3 * 104].
  • -1000 <= Node.val <= 1000
				
					# time complexity: O(n)
# space complexity: O(n)
from typing import Optional


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


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

        def dfs(node: Optional[TreeNode]):
            nonlocal maxPath
            if node is None:
                return 0
            pathLeft = max(dfs(node.left), 0)
            pathRight = max(dfs(node.right), 0)
            maxPath = max(maxPath, pathLeft + pathRight + node.val)
            return max(pathLeft + node.val, pathRight + node.val)
        dfs(root)
        return maxPath


root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
print(Solution().maxPathSum(root))
				
			

Binary Tree Maximum Path Sum 解題思路

這題的難點在於「路徑可以不經過根、也可以在某個節點轉彎」。解法是讓遞迴回傳「以此節點為端點、向下延伸的最大單邊和」,同時在每個節點用「左單邊 + 節點值 + 右單邊」去更新全域答案——回傳值與答案更新是兩件不同的事,分清楚就不難。

Binary Tree Maximum Path Sum 演算法步驟

  1. 定義 gain(node):節點為 null 回傳 0。
  2. 遞迴取得左右子樹的單邊增益,並與 0 取大(負增益不如不取)。
  3. 用 node.val + leftGain + rightGain 更新全域最大值(代表在此節點轉彎的路徑)。
  4. 回傳 node.val + max(leftGain, rightGain),因為往上延伸時只能選一邊。

Binary Tree Maximum Path Sum 複雜度分析

項目複雜度
時間複雜度O(n)
空間複雜度O(h)

每個節點被走訪一次並做常數次運算,時間為 O(n)。空間為遞迴堆疊深度 O(h),最壞 O(n)。

Binary Tree Maximum Path Sum 的邊界情況與常見錯誤

  • 全域答案要初始化為負無限,因為所有節點都可能是負值。
  • 子樹增益為負時要截斷成 0,否則會拖累答案。
  • 回傳值只能選一邊,若回傳兩邊之和會讓上層形成非法路徑。
  • 單節點樹的答案就是該節點值,即使是負數。

Binary Tree Maximum Path Sum 其他解法比較

解法時間空間說明
列舉所有節點配對的路徑O(n²)O(h)完全不可行
先求任兩點距離再求最大O(n²)O(n)過度複雜
後序遞迴 + 全域更新O(n)O(h)本文採用