/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxPathSum(TreeNode root){
if(root.left == null && root.right == null){
return root.val;
}
return maxPathSum2(root).maxV;
}
private ReturnWrapper maxPathSum2(TreeNode root) {
if(root == null){
return new ReturnWrapper(-2000, -2000, -2000);
}
ReturnWrapper rightMaxPath = maxPathSum2(root.right);
ReturnWrapper leftMaxPath = maxPathSum2(root.left);
int rootVal = root.val;
int newEdgeV = Math.max(root.val, root.val + Math.max(rightMaxPath.edgeV, leftMaxPath.edgeV));
int newSumV = Math.max(Math.max(root.val, root.val + rightMaxPath.edgeV + leftMaxPath.edgeV), root.val + Math.max(rightMaxPath.edgeV, leftMaxPath.edgeV));
int newMaxV = Math.max(Math.max(newSumV, leftMaxPath.maxV), rightMaxPath.maxV);
return new ReturnWrapper(newMaxV, newSumV, newEdgeV);
}
class ReturnWrapper{
private int maxV;
private int sumV;
private int edgeV;
public ReturnWrapper(int maxV, int sumV, int edgeV){
this.maxV = maxV;
this.sumV = sumV;
this.edgeV = edgeV;
}
public ReturnWrapper(){
}
private boolean optimalIncludesRoot(){
return maxV == sumV;
}
private boolean isAnEdge(){
return sumV == edgeV;
}
}
}
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)