当路径到达某个节点时,该路径既可以前往它的左子树也可以前往它的右子树,但如果路径同时经过它的左右子树,那么就不能经过它的父节点。
class Solution {
int maxSum = Integer . MIN_VALUE;
public int maxPathSum ( TreeNode root) {
dfs ( root) ;
return maxSum;
}
public int dfs ( TreeNode root) {
if ( root == null ) return 0 ;
int left = dfs ( root. left) ;
int right = dfs ( root. right) ;
if ( left >= 0 && right >= 0 ) {
maxSum = Math . max ( maxSum, left + right + root. val) ;
} else if ( left < 0 && right < 0 ) {
maxSum = Math . max ( maxSum, root. val) ;
return root. val;
}
maxSum = Math . max ( maxSum, root. val + Math . max ( left, right) ) ;
return root. val + Math . max ( left, right) ;
}
}
class Solution {
int maxSum = Integer . MIN_VALUE;
public int maxPathSum ( TreeNode root) {
dfs ( root) ;
return maxSum;
}
public int dfs ( TreeNode root) {
if ( root == null ) return 0 ;
int left = Math . max ( dfs ( root. left) , 0 ) ;
int right = Math . max ( dfs ( root. right) , 0 ) ;
maxSum = Math . max ( maxSum, left + right + root. val) ;
return root. val + Math . max ( left, right) ;
}
}