LeetCode 124. Binary Tree Maximum Path Sum

For each node, there may be several conditions: 

1. root.left <0 and root.right <0, the max will be root.val

2.root.left or root.right < 0, the max will be root.val + root.left/right

3.no one <0, max will be root.val + root.left + root.right

However, for nodes except the root, what we return is not root.val + both, instead, we only choose one substree + root.val so that we avoid branching. What we return is only for calculating the max of the parent node.  

class Solution {

    int result = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {

        helper(root);

        return result;


    }


    public int helper(TreeNode root){

        if(root == null) return 0;

        int first = Math.max(0, helper(root.left));

        int second = Math.max(0,helper(root.right));

        result = Math.max(result, first + second + root.val); // It's possible that the max is any substree node, so we calculate the total value every step

        return root.val + Math.max(first,second); // however, for calculating the parent, we only return the max substree+node.val inorder to avoid branches

    }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。