• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: Binary Tree Maximum Path Sum

这题比较难,没理顺关系,做了很多次还只是过了small judge,于是去看网上答案,然后再改了改,关键在于local_max和globe_max,globe_max要随时改得,而maxsum函数只是返回最大路径

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int maxSum(TreeNode * root, int & globe_max){  
13         if(!root) {  
14             return 0;  
15         }  
16         int local_max = root->val;  
17         int left = maxSum(root->left, globe_max);  
18         int right = maxSum(root->right, globe_max);  
19         local_max = max(local_max, local_max+left);
20         local_max = max(local_max, local_max+right);
21         globe_max = max(globe_max, local_max);  
22         return max(root->val, max(root->val+right, root->val+left) );  
23     }  
24     int maxPathSum(TreeNode *root) {
25         // Start typing your C/C++ solution below
26         // DO NOT write int main() function
27         int globe_max = root->val;  
28         int maxVal = maxSum(root, globe_max);  
29         return max(globe_max, maxVal);  
30     }
31 };

 C#:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left;
 6  *     public TreeNode right;
 7  *     public TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int maxSum(TreeNode root, ref int globeMax)
12     {
13         if (root == null) return 0;
14         int localMax = root.val;
15         int left = maxSum(root.left, ref globeMax);
16         int right = maxSum(root.right, ref globeMax);
17         localMax = Math.Max(localMax, localMax + left);
18         localMax = Math.Max(localMax, localMax + right);
19         globeMax = Math.Max(globeMax, localMax);
20         return Math.Max(root.val, Math.Max(root.val + left, root.val + right));
21     }
22     public int MaxPathSum(TreeNode root) {
23         int globeMax = root.val;
24         int maxVal = maxSum(root, ref globeMax);
25         return Math.Max(globeMax, maxVal);
26     }
27 }
View Code

 

posted @ 2013-03-19 11:13  ying_vincent  阅读(190)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3