LeetCode 30 days Challenge - Day 29
本系列將對LeetCode新推出的30天算法挑戰進行總結記錄,旨在記錄學習成果、方便未來查閱,同時望爲廣大網友提供幫助。
Binary Tree Maximum Path Sum
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]
1
/ \
2 3
Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
Output: 42
Solution
題目要求分析:給定一棵非空二叉樹,求其中最大路徑和。注意此處的路徑不一定經過根結點,路徑至少有一個節點。
解法:
本題需要注意的是,存在負數結點值,傳統的遞歸思想無法滿足題目要求。
對於當前結點,維護一個最大值變量res,我們需要考慮:
-
路徑不允許分叉,那麼若當前結點存在父節點、經過當前結點、還要向父節點走的路徑只可能經過當前結點的左右子樹之一,該定義是遞歸的。在下文,稱這種情況爲
無分叉子樹
-
最終經過當前結點的最大路徑只有四種情況:
-
經過當前結點、不經過子樹:
無分叉子樹最大路徑和都爲負數
res = max(res, node->val + max(0, l) + max(0, r));
-
經過當前結點、當前節點的左子樹、當前節點的右子樹:
兩顆無分叉子樹最大路徑和都不爲負數
res = max(res, node->val + max(0, l) + max(0, r));
-
經過當前結點、當前節點的左子樹:
右無分叉子樹最大路徑和不爲負數
更新無分叉子樹的最大路徑和:
node->val += max(0, max(l, r));
-
經過當前結點、當前節點的右子樹:
左無分叉子樹最大路徑和不爲負數
更新無分叉子樹的最大路徑和:
node->val += max(0, max(l, r));
-
按以上思路,題解如下:
int getSubPathSum(TreeNode* node, int &res) {
if(!node) return 0;
int l = getSubPathSum(node->left, res);
int r = getSubPathSum(node->right, res);
res = max(res, node->val + max(0, l) + max(0, r));
node->val += max(0, max(l, r));
return node->val;
}
int maxPathSum(TreeNode* root) {
int res = INT_MIN;
getSubPathSum(root, res);
return res;
}
傳送門:Binary Tree Maximum Path Sum
2020/4 Karl