题目描述
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.
Example1:
Input: [1,2,3]
1
/ \
2 3
Output: 6
Example2:
Input: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
Output: 42
解题思路
- 参考
- 我们现在要求最大路径和,那么就要分别得到左右两条路径的最大和。
- 而左路径的最大和为左节点的值加上它左右路径中较大的路径和,(这也是最后一步 函数返回的时候 root -> val + max(left, right))
- 右路径最大和为右节点的值加上它左右路径中较大的路径和。
- 注意:如果某条子路径的左右节点为负,直接置为0,等于不走这个节点。
/**
* 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 maxPathSum(TreeNode* root) {
if(root == nullptr){
return 0;
}
int maxSum = INT_MIN;
dfsMaxSum(root, maxSum);
return maxSum;
}
int dfsMaxSum(TreeNode* root, int& maxSum){
if(root == nullptr){
return 0;
}
int left = max(0, dfsMaxSum(root -> left, maxSum)); // 当前路径的最大和,我们需要分别得到左右两条路径的最大和
int right = max(0, dfsMaxSum(root -> right, maxSum));
maxSum = max(maxSum, left + right + root -> val);
return root -> val + max(left, right); // 左路径的最大和为左节点的值加上它左右路径中较大的路径和,右路径最大和为右节点的值加上它左右路径中较大的路径和
}
};