码迷,mamicode.com
首页 > 其他好文 > 详细

124. Binary Tree Maximum Path Sum

时间:2018-07-19 13:39:35      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:hang   code   style   ted   min   value   maximum   ber   bec   

//   // Time Limit Exceeded  because of the use of
   int left = maxSum(root.left) > 0 ? maxSum(root.left) : 0;

class Solution {
    int max = Integer.MIN_VALUE; // changed from 0, because in the case, the tree is a node, negative number 
    public int maxPathSum(TreeNode root) {
      maxSum(root);
      return max;

    }
    private int maxSum(TreeNode root){
      if(root == null){
        return 0;
      }
      
      
      // Time Limit Exceeded 
      int left = maxSum(root.left) > 0 ? maxSum(root.left) : 0;
      int right = maxSum(root.right) > 0 ? maxSum(root.right) : 0;
      
      int current_sum = left + right + root.val;
      
      max = Math.max(current_sum, max);
      return Math.max(left, right) + root.val;
    }
}

  ///////////////// this is accepted 
class Solution {
    int max = Integer.MIN_VALUE; // changed from 0, because in the case, the tree is a node, negative number 
    public int maxPathSum(TreeNode root) {
      maxSum(root);
      return max;

    }
    private int maxSum(TreeNode root){
      if(root == null){
        return 0;
      }
      int left = Math.max(0, maxSum(root.left));
      int right = Math.max(0, maxSum(root.right));
      int current_sum = left + right + root.val;
      max = Math.max(current_sum, max);
      return Math.max(left, right) + root.val;
    }
}

 

124. Binary Tree Maximum Path Sum

标签:hang   code   style   ted   min   value   maximum   ber   bec   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9335061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!