Last Updated on 2022-12-11 by Clay
題目
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
題目給定一顆二元樹,我們要找到一條路徑(path)且能讓該路徑上所有節點值達到最大。在這條路徑中,可以不包含根節點(root)。
解題思路
DFS(深度優先搜索)
要遍歷一顆樹,最常見的方法之一就是深度優先搜索(DFS)。但這題由於需要找到一條路徑(path)來讓加總值達到最大,所以需要在 DFS 的遞迴函式中做三件事:
- 左右節點的 DFS 函式返回值若小於 0(因為節點可能為負值,所以底下節點的加總值可能為負數),則取 0。這意味著『不走底下的路徑』來讓路徑加總值最大化
- 在 DFS 遞迴函式中的返回值,由於我們只能『走一條路』,所以是返回左右節點兩條路徑中加總值比較大的那條
- 每個遞迴式中,都要不斷更新最終的加總值,這是為了要取最大值。而這個加總值的判斷方式是
max(currMaxSum, DFS(node->left)+DFS(node->right)+node->val)
,實際意義就是從其中一個葉子節點都走最大路徑、通過當前節點、再走另一個方向的結點到底的最大值路徑。
詳細情況請看範例程式。
DFS 複雜度
Time Complexity | O(n) |
Space Complexity | O(1) |
C++ 範例程式碼
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int DFS(TreeNode* root, int& maxSum) {
// Base case
if (!root) {
return 0;
}
int leftSum = max(0, DFS(root->left, maxSum));
int rightSum = max(0, DFS(root->right, maxSum));
// Take the max value
maxSum = max(maxSum, leftSum+rightSum+root->val);
return max(leftSum, rightSum) + root->val;
}
int maxPathSum(TreeNode* root) {
int maxSum = INT_MIN;
DFS(root, maxSum);
return maxSum;
}
};
Python 範例程式碼
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def DFS(self, root: Optional[TreeNode]) -> int:
# Base case
if not root:
return 0
left_sum = max(0, self.DFS(root.left))
right_sum = max(0, self.DFS(root.right))
# Take the maximum sum
self.max_sum = max(self.max_sum, left_sum+right_sum+root.val)
return max(left_sum, right_sum) + root.val
def maxPathSum(self, root: Optional[TreeNode]) -> int:
# According to `Constraints`, the minimum node value is 1,000
self.max_sum = -1001
self.DFS(root)
return self.max_sum