Question

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

Thinking:

  • Method1:递归
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int result = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root){
        maxSum(root);
        return result;
    }
    public int maxSum(TreeNode root){
        if(root == null) return 0;
        int leftSum = maxSum(root.left);
        int rightSum = maxSum(root.right);
        int cur = root.val;
        int res = cur + ((leftSum > 0) ? leftSum:0) + ((rightSum > 0) ? rightSum:0); //包括当前节点的树的最大值。
        this.result = Math.max(result, res);
        return Math.max(cur, Math.max(cur + leftSum, cur + rightSum)); //返回到上一层的可能性有三种, 只返回当前结点,左结点往上, 右结点往上。
    }
}

二刷

这代替还是比较难想,但是想出结果了就很好写。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int result = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        if(root == null) return 0;
        maxSum(root);
        return this.result;
    }
    private int maxSum(TreeNode node){
        if(node == null) return 0;
        int left = maxSum(node.left);
        int right = maxSum(node.right);
        int res = node.val + ((left > 0) ? left: 0) + ((right > 0) ? right: 0);
        result = Math.max(res, result);
        return Math.max(node.val, Math.max(node.val + left, node.val + right));
    }
}