/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
     int ans = Integer.MIN_VALUE;
    public int maxPathSum (TreeNode root) {
        // write code here
        if(root == null){
            return 0;
        }
        dfs(root);
        return ans;
    }
    private 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);
        ans = Math.max(ans, root.val +leftMax + rightMax);
        
        return root.val + Math.max(leftMax, rightMax);
    }
}