描述
路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。
路径和 是路径中各节点值的总和。
给你一个二叉树的根节点 root ,返回其 最大路径和 。
示例1:
输入:root = [1,2,3]
输出:6
解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6
示例2:
输入:root = [-10,9,20,null,null,15,7]
输出:42
解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
提示:
- 树中节点数目范围是 [1, 3 * 10^4]
- -1000 <= Node.val <= 1000
思路
对于每一个节点,若最终的最大路径中包括了该节点,那么只能是:
- 1.要么该节点的左右子树中的较大路径的子树连同该节点及该节点的父节点之前的节点在最大路径中;
- 2.要么该节点的左右子树连同该节点在最大路径中。
如果某节点的左子树或右子树最大路径为负值,则代表此子树的最大值的变量maxL或maxR的值设为为0,表示不包含此子树的路径;如果为正则设为此值。
如果属于情况2,则使用maxVal记录最大值,最终返回;如果属于情况1,则最终返回左右子树中较大的路径值+此节点的值。
解答
class Solution {
public:
int MIN_VALUE = -2147483648;
int maxVal = MIN_VALUE;
int recurrence(TreeNode* root){
if(root == nullptr) return 0;
int maxL = max(recurrence(root->left), 0);
int maxR = max(recurrence(root->right), 0);
maxVal = max(maxVal, maxL + maxR + root->val);//情况2
return max(maxL, maxR) + root->val;//情况1
}
int maxPathSum(TreeNode* root) {
recurrence(root);
return maxVal;
}
};