题目
https://www.nowcoder.com/practice/da785ea0f64b442488c125b441a4ba4a?tpId=190&&tqId=35180&rp=1&ru=/ta/job-code-high-rd&qru=/ta/job-code-high-rd/question-ranking
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型
*/
public static int maxValue;
public int maxPathSum (TreeNode root) {
// write code here
maxValue = Integer.MIN_VALUE;
getMaxPathSum(root);
return maxValue;
}
public int getMaxPathSum(TreeNode root){
if(root != null){
int maxLeftValue = Math.max(0,getMaxPathSum(root.left));
int maxRightValue = Math.max(0,getMaxPathSum(root.right));
maxValue = Math.max(maxValue,maxLeftValue + root.val + maxRightValue);
return Math.max(maxLeftValue , maxRightValue)+ root.val;
}
return 0;
}
}
全部评论
(1) 回帖