[LeetCode 124] Binary Tree Maximum Path Sum (hard)

Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42
image.png
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxPathSum(TreeNode root) {
        if (root == null) {
            return Integer.MIN_VALUE;
        }
        
        int[] maxSum = { Integer.MIN_VALUE };
        maxPathSumHelper (root, maxSum);
        
        return maxSum [0];
    }
    
    private int maxPathSumHelper (TreeNode root, int[] maxSum) {
        if (root == null) {
            return 0;
        }
        
        // 如果得到的max是负数,那么对于求maxSum没有贡献,直接忽略,取成0
        int leftMax = Math.max (maxPathSumHelper (root.left, maxSum), 0);
        int rightMax = Math.max (maxPathSumHelper (root.right, maxSum), 0);
        int currentMax = root.val + leftMax + rightMax;
        
        // update maxSum
        maxSum [0] = Math.max (maxSum[0], currentMax);
        
        // return a path containning root node and make max path sum
        return root.val + Math.max (leftMax, rightMax); 
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,490评论 0 10
  • 梦是对潜意识最直接的反映,但梦对潜意识的反映却一点都不直接。 梦见考试往往是心里有压力的表现,而梦中考得好坏反映的...
    踢车刘阅读 185评论 0 0
  • 1.别让家人看见丢弃的物品,这样家人会认为我们很浪费,总是舍不得丢,结果使用的机会也会很少 2.整理就是自己和自己...
    Aimee1314阅读 254评论 1 1