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
原文地址:https://www.cnblogs.com/yingzhongwen/p/2968756.html