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

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

给定一个非空二叉树,返回其最大路径和。

本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

示例 1:

输入: [1,2,3]

       1
      / 
     2   3

输出: 6

示例 2:

输入: [-10,9,20,null,null,15,7]

   -10
   / 
  9  20
    /  
   15   7

输出: 42

思路:分治+递归

二叉树的最大值等于其所有子树的最大值中的最大值,对于叶子节点其最大值等于他本身;

package LeetCode;

/**
 * @ClassName Q124
 * @Description
 *
 * @Author m
 * @Version 1.0
 */
public class Q124 {

    int max = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        if(root == null) return 0;

        dfs(root);
        return max;
    }

    /**
     * 通过递归查找当前节点往下走能获得的最大值,
     * 过程中不断更新最大值
     * @param root
     * @return
     */
    public int dfs(TreeNode root){

        //如果为空则返回0
        if(root == null) {
            return 0;
        }

        //分别计算左右节点的最大值,如果小于0按0算,即不继续往下走
        int leftGain = Math.max(dfs(root.left),0);
        int rightGain = Math.max(dfs(root.right),0);

        //更新最大值,这里是找当前子树所能获得的最大结果,是局部最大值,
        // 通过不断比较局部最大值获得全局最大值,即分治的思想
        max = Math.max(max, root.val+leftGain+rightGain);

        //返回当前结点的最大值
        return root.val + Math.max(leftGain,rightGain);
    }
}

因为我喜欢追寻过程中的自己
原文地址:https://www.cnblogs.com/IzuruKamuku/p/14359766.html