CODE:
路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。
路径和 是路径中各节点值的总和。
给你一个二叉树的根节点 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 * 104]
-1000 <= Node.val <= 1000来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
CODE:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int maxSum = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { maxGain(root); return maxSum; } public int maxGain(TreeNode node) { if (node == null) { return 0; } int leftSum = Math.max(maxGain(node.left), 0);//左侧最大贡献值 int rightSum = Math.max(maxGain(node.right), 0);//右侧最大贡献值 int sum = node.val + leftSum + rightSum;//当前节点最大路径和 if (sum > maxSum) { maxSum = sum; } return node.val + Math.max(leftSum, rightSum);//该节点最大贡献值 } }
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxPathSum(self, root: Optional[TreeNode]) -> int: self.maxVal = -inf if not root: return 0 self.maxGain(root) return self.maxVal def maxGain(self, node:TreeNode) -> int: if not node: return 0 leftVal = max(0, self.maxGain(node.left)) rightVal = max(0, self.maxGain(node.right)) val = node.val self.maxVal = max(val+leftVal+rightVal, self.maxVal) return val+max(leftVal, rightVal)
NOTES:
1. 最大路径和=某节点val+max(左侧贡献值,0)+max(右侧贡献值,0)
2. 某节点最大贡献值=该节点val+max(max(左侧贡献值,0),max(右侧贡献值,0))
3. 贡献值为负数,取0为还不如不走这个路径