本题的关键在于读懂题目,对路径的定义,是最大路径和而不是最大子树和
public class Solution {
int res;
public int maxPathSum(TreeNode root) {
res = Integer.MIN_VALUE;
dfs(root);
return res;
}
//后根遍历,算的是一颗完整树的和
public int dfs(TreeNode p){
if(p==null) return 0;
int left = Math.max(0,dfs(p.left));
int right = Math.max(0,dfs(p.right));
res = Math.max(left+right+p.val,res);
return Math.max(left,right)+p.val;
}
}