class Solution { public int maxPathSum(TreeNode root) { dfs(root); return res; } int res = Integer.MIN_VALUE; public int dfs(TreeNode root) { // 返回以当前根节点结尾的子树最大路径和 if(root == null) return 0; int left = dfs(root.left); int right = dfs(root.right); res = Math.max(res,left + right + root.val); return Math.max(0,root.val + Math.max(left,right)); // 小于0就去除 } }