class Solution {
private int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null) {
return 0;
}
dfs(root);
return max;
}
// 返回经过root的单边分支最大和
public int dfs(TreeNode root) {
if (root == null) {
return 0;
}
int leftMax = Math.max(dfs(root.left), 0);
int rightMax = Math.max(dfs(root.right), 0);
max = Math.max(max, root.val + leftMax + rightMax);
return root.val + Math.max(leftMax, rightMax);
}
}