public class Leetcode124 { int res = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { dfs(root); return res; } public int dfs(TreeNode node) { if (node == null) return 0; // 递归计算左右节点的最大贡献值,如果为父,就不计算到以当前节点为根节点的最大路径中 int leftNodeSum = Math.max(dfs(node.left),0); int rightNodeSum = Math.max(dfs(node.right),0); //更新答案 int temp = node.val + leftNodeSum + rightNodeSum; res = Math.max(res, temp); return node.val + Math.max(leftNodeSum, rightNodeSum); } }