要注意两个逻辑:
递归更新ans的值
① 跟最终结果ans比大小时,要用“穿过当前节点的路径”,也就是左右子树可以一起选
②递归返回上一层时,要选左右子树最多只能选一个,或者不选。当组成的最大值为负数时直接返回0
/**
* 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 {
int ans = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
ans = root.val;
findmax(root);
return ans;
}
public int findmax(TreeNode root){
int tem = root.val;
ans = Math.max(ans,tem);
int leftmax = 0, rightmax = 0;
if(root.left != null)
leftmax = findmax(root.left);
if(root.right != null)
rightmax = findmax(root.right);
ans = Math.max(ans,tem + leftmax + rightmax);
if(Math.max(leftmax,rightmax) > 0)
tem+=Math.max(leftmax,rightmax);
if(tem<0)
return 0;
return tem;
}
}