Binary Tree Maximum Path Sum(二叉树中的最大路径和)

http://www.lintcode.com/en/problem/binary-tree-maximum-path-sum/?rand=true

``````/**
* 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 int maxPathSum(TreeNode root) {
return tree(root).maxPath;
}

private Node tree(TreeNode root) {
Node node = new Node(0, Integer.MIN_VALUE);
if (root == null) {
return node;
}
Node left = tree(root.left);
Node right = tree(root.right);
//        singlePath还可以再添加节点，所以不能形成交叉，只能是左边或者右边跟当前节点，
node.singlePath = Math.max(node.singlePath, Math.max(left.singlePath, right.singlePath) + root.val);
//        maxPath可能是两边的各自最大值，也可能是两加连上当前节点
node.maxPath = Math.max(Math.max(left.maxPath, right.maxPath), left.singlePath + right.singlePath + root.val);
return node;
}

private class Node {
//可以添加节点的路径和
int singlePath;
//不可以添加节点的路径和
int maxPath;

public Node(int singlePath, int maxPath) {
this.singlePath = singlePath;
this.maxPath = maxPath;
}
}
}
``````