[解题报告]Binary Tree Maximum Path Sum

题目:

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

Example

Given the below binary tree:

  1
 / \
2   3

return 6.

思路:

计算树的最长path有2种情况:

1. 通过根的path.

  (1)如果左子树从左树根到任何一个Node的path大于零,可以链到root上

  (2)如果右子树从右树根到任何一个Node的path大于零,可以链到root上

2. 不通过根的path. 这个可以取左子树及右子树的path的最大值。

所以创建一个inner class:

记录2个值:

1. 本树的最大path。

2. 本树从根节点出发到任何一个节点的最大path.

注意,当root == null,以上2个值都要置为Integer_MIN_VALUE; 因为没有节点可取的时候,是不存在solution的。以免干扰递归的计算

因为有Integer.MIN_VALUE的出现,所以在相加时要考虑越界情况,做判断。

ps:之前一直用C++刷,突然决定要改Java了,发现。。。还是Java简单。。。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
    public class ReturnType{
        int maxPath;
        int singlePath;
        ReturnType(int max, int single){
            this.maxPath = max;
            this.singlePath = single;
        }
    }
    public ReturnType maxPath(TreeNode root){
        ReturnType res = new ReturnType(Integer.MIN_VALUE, Integer.MIN_VALUE);
        if (root == null) {
            return res;
        }
        // divide
        ReturnType left = maxPath(root.left);
        ReturnType right = maxPath(root.right);
        
        // conquer
        // 直接加有可能越界,singlePath小于零则当前singlePath = root.val
        int increaseLeft = Math.max(left.singlePath, 0);
        int increaseRight = Math.max(right.singlePath, 0);
        res.singlePath = Math.max(increaseLeft + root.val, increaseRight + root.val);
        
        // 直接加有可能越界
        res.maxPath = Math.max(right.maxPath, left.maxPath);
        res.maxPath = Math.max(res.maxPath, increaseLeft + increaseRight + root.val);
        return res;
    }
    public int maxPathSum(TreeNode root) {
        // write your code here
        return maxPath(root).maxPath;
    }
}

ref:http://www.cnblogs.com/yuzhangcmu/p/4172855.html 

posted @ 2015-09-17 11:28  Nily  阅读(165)  评论(0)    收藏  举报