题目

var maxPathSum = function(root) {
  if(!root)return 0;
  let num = root.val;
  let left = get(root.left);
  let right = get(root.right);
  let ans = (left<0?0:left) + root.val + (right<0?0:right);
  function get(root){
    if(!root)return 0;
    let left = get(root.left);
    let right = get(root.right);
    num = Math.max(num,(left<0?0:left)+(right<0?0:right)+root.val);
    return Math.max((left<0?0:left),(right<0?0:right))+root.val;
  }
  ans = Math.max(ans,num);
  return ans;
};
var maxPathSum = function(root) {
  let max = root.val;
  function dfs(root){
    if(!root)return 0;
    let num = root.val;
    let left = dfs(root.left);
    let right = dfs(root.right);
    let ans = left + right + root.val;
    max = Math.max(max,ans);
    const temp = root.val + Math.max(left,right);
    return temp<=0?0:temp;
  }
  dfs(root);
  return max;
};