124. 二叉树中的最大路径和

 

 

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就去除

    }
}

 

posted @ 2020-07-14 17:35  Sexyomaru  阅读(122)  评论(0编辑  收藏  举报