一、题目内容

image.png

二、题解

解法1:

思路

左右子树贡献值求最大

代码

  1. public class Solution {
  2. int ans = Integer.MIN_VALUE;
  3. public int maxPathSum (TreeNode root) {
  4. if(root == null){
  5. return 0;
  6. }
  7. recur(root);
  8. return ans;
  9. }
  10. public int recur(TreeNode root){
  11. if (root == null) {
  12. return 0;
  13. }
  14. int leftMax = Math.max(recur(root.left),0);
  15. int rightMax = Math.max(recur(root.right),0);
  16. ans = Math.max(ans,root.val+leftMax+rightMax);
  17. return root.val+Math.max(leftMax,rightMax);
  18. }
  19. }