/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ classSolution{ int res = Integer.MIN_VALUE; publicintmaxPathSum(TreeNode root){ maxPath(root); return(res); } publicintmaxPath(TreeNode root){ if(root == null) return0; int left = Math.max(0,maxPath(root.left)); int right = Math.max(0,maxPath(root.right)); //左根右 res = Math.max(res,left+right+root.val); //这个返回注意,返回节点的最大贡献值 //对应结果,左-根-根父,右-根-根父 return Math.max(left,right)+root.val; } }