image.png

解题思路

image.png

  1. class Solution {
  2. int res = Integer.MIN_VALUE;
  3. public int maxPathSum(TreeNode root) {
  4. helper(root);
  5. return res;
  6. }
  7. private int helper(TreeNode root) {
  8. if (root == null) return 0;
  9. //左边最大值
  10. int left = helper(root.left);
  11. //右边最大值
  12. int right = helper(root.right);
  13. //和全局变量比较
  14. res = Math.max(left + right + root.val, res);
  15. // >0 说明都能使路径变大
  16. return Math.max(0, Math.max(left, right) + root.val);
  17. }
  18. }