
写法1
class Solution {
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
dfs(root);
return max;
}
public int dfs(TreeNode node) {
if (node == null) {
return 0;
}
int leftSum = Math.max(0, dfs(node.left));
int rightSum = Math.max(0, dfs(node.right));
int curSum = leftSum + rightSum + node.val;
max = Math.max(curSum, max);
return Math.max(leftSum, rightSum) + node.val;
}
}
class Solution {
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null) {
return 0;
}
dfs(root);
return max;
}
public int dfs(TreeNode node) {
if (node == null) {
return 0;
}
int leftSum = Math.max(0, dfs(node.left));
int rightSum = Math.max(0, dfs(node.right));
max = Math.max(leftSum + rightSum + node.val, max);
return Math.max(leftSum, rightSum) + node.val;
}
}
写法2
class Solution {
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null) {
return 0;
}
dfs(root);
return max;
}
public int dfs(TreeNode node) {
if (node == null) {
return 0;
}
int leftSum = dfs(node.left);
int rightSum = dfs(node.right);
max = Math.max(leftSum + rightSum + node.val, max);
return Math.max(0, Math.max(leftSum, rightSum) + node.val);
}
}