[LeetCode] 124. Binary Tree Maximum Path Sum Java

题目:

Given a 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.

For example:
Given the below binary tree,

       1
      / 
     2   3

Return 6.

题意及分析:一个二叉树,求以父子节点关系连接起来的最大路径。 取当前点和左右边加和,当前点的值中最大的作为本层返回值。并在全局维护一个max。若路径经过一个点,那么对于当前点有四种情况,一种是只经过该点就截止,一种是该点加上左子节点的最大值,另一种是该点加上右子节点的值,最后一种是该点左右子树加上该点的值,比较四种情况就能得到在该点能取得的最大值,最后与全局的最大值比较。终能得到的结果就是最大值。

代码:

class Solution {
    public int maxPathSum(TreeNode root) {      //最大路径出现在叶子节点之间
        // if(root == null) return 0;
        int[] result = new int[1];
        result[0] = Integer.MIN_VALUE;

        findMaxSum(root,result);
        return result[0];
    }

    private int findMaxSum(TreeNode node,int[] result){
        if(node == null)
            return 0;

        int left = findMaxSum(node.left,result);
        int right = findMaxSum(node.right,result);

        int ans = Math.max(node.val,Math.max(left+node.val,right+node.val));        //记录从当前点经过能得到的最大值

        result[0] = Math.max(result[0],Math.max(ans,left+right+node.val));      //先比较从当前点向能得到的最大值和以该点左右子树能得到的最大值,然后和原来的最大值比较

        return ans;
    }
}
原文地址:https://www.cnblogs.com/271934Liao/p/7766315.html