給定一個非空二叉樹,返回其最大路徑和。
本題中,路徑被定義爲一條從樹中任意節點出發,達到任意節點的序列。該路徑至少包含一個節點,且不一定經過根節點。
示例 1:
輸入: [1,2,3] 1 / \ 2 3 輸出: 6
示例 2:
輸入: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \ 15 7 輸出: 42
分析:給定一個非空節點,最終路徑經過這個節點有4種情況:1.只有該節點本身(左右子樹的路徑都是負數);2.該節點+左子樹路徑;3.該節點+右子樹路徑;4.該節點+左子樹路徑+右子樹路徑。其中1,2,3都可以作爲子樹路徑和向上延伸,而4則不行。
代碼如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int result;
int maxPathSum(TreeNode* root) {
result = INT_MIN; // 考慮全部節點爲負數的情況
getPath(root);
return result;
}
int getPath(TreeNode* node) {
if(node == NULL) {
return 0;
}
int left = getPath(node->left);
int right = getPath(node->right);
int tmp = max(max(left+node->val, right+node->val), node->val); // 這三種情況是經過節點node且可以向上組合的,需要返回給上層使用
result = max(result,max(tmp, left+right+node->val)); // 不能向上組合的情況只需要用於更新結果,無需向上返回
return tmp;
}
};