124. Binary Tree Maximum Path Sum
题目大意
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.
中文释义
在二叉树中,一条路径是指节点序列,其中序列中每对相邻的节点之间都有一条边连接。一个节点在序列中最多只能出现一次。注意,路径不需要通过根节点。
路径的路径和是该路径上所有节点值的总和。
给定一个二叉树的根节点,返回任何非空路径的最大路径和。
示例
示例 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
解题思路
方法
该方法通过递归地遍历二叉树的每个节点,计算以每个节点为根的子树的最大路径和。
-
递归函数 maxPathDown:
- 实现
maxPathDown
函数递归地计算从当前节点到叶节点的最大路径和。 - 函数同时更新一个引用参数
maxSum
,它记录遍历过程中的最大路径和。
- 实现
-
处理左右子树:
- 计算左子树和右子树的最大路径和,忽略负值路径和。
-
更新最大路径和:
- 更新
maxSum
为当前节点值加上左右子树的最大路径和,如果这个总和大于当前的maxSum
。
- 更新
-
返回节点的最大贡献值:
- 返回当前节点的值加上左右子树中较大的路径和。
-
计算总的最大路径和:
- 在
maxPathSum
函数中,初始化maxSum
为最小整数值,然后调用maxPathDown
函数并返回maxSum
。
- 在
代码
class Solution {
public:
int maxPathDown(TreeNode* root, int& maxSum) {
if (root == nullptr) return 0;
int left = max(0, maxPathDown(root -> left, maxSum));
int right = max(0, maxPathDown(root -> right, maxSum));
maxSum = max(maxSum, left + right + root -> val);
return max(left, right) + root -> val;
}
int maxPathSum(TreeNode* root) {
int maxSum = INT_MIN;
maxPathDown(root, maxSum);
return maxSum;
}
};