package medium;
/**
* Date 2019-02-25 19:48
* Description:给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)
*/
public class Leetcode94 {
private class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
}
}
private class Result {
int onePath;
int maxPath;
public Result(int onePath, int maxPath) {
this.onePath = onePath;
this.maxPath = maxPath;
}
}
public int maxPathSum(TreeNode root) {
return helper(root).maxPath;
}
private Result helper(TreeNode root) {
if (root == null) {
return new Result(0, Integer.MIN_VALUE);
}
Result left = helper(root.left);
Result right = helper(root.right);
int onePath = Math.max(left.onePath, right.onePath) + root.val;
onePath = Math.max(onePath,0);
int maxPath = Math.max(left.maxPath, right.maxPath);
maxPath = Math.max(maxPath, left.onePath + right.onePath + root.val);
return new Result(onePath, maxPath);
}
}