[LintCode]Binary Tree Maximum Path Sum
/**
* 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.
*/
private class RstType {
int maxPath;
int singlePath;
public RstType(int s, int m) {
singlePath = s;
maxPath = m;
}
}
private RstType helper(TreeNode root) {
if (root == null) {
return new RstType(0, Integer.MIN_VALUE);
}
// divide
RstType left = helper(root.left);
RstType right = helper(root.right);
// conquer
int singlePath = Math.max(0,
root.val + Math.max(left.singlePath, right.singlePath));
int maxPath = Math.max(Math.max(left.maxPath, right.maxPath),
root.val + left.singlePath + right.singlePath);
return new RstType(singlePath, maxPath);
}
public int maxPathSum(TreeNode root) {
// 2015-3-23
RstType rst = helper(root);
return rst.maxPath;
}
}