标签:
Use lMax get the maximum value of a sub SINGLE branch (left branch or right branch or just current node).
Use gMax get the maximum value of the whole sub branch (include current node). So gMax need to pass by reference.
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 getSum(TreeNode *root, int &gMax) { 13 if (!root) return 0; 14 int lValue = getSum(root->left, gMax), rValue = getSum(root->right, gMax), total = root->val; 15 total += lValue > 0 ? lValue : 0; 16 total += rValue > 0 ? rValue : 0; 17 gMax = max(total, gMax); 18 return max(max(root->val, root->val + lValue), root->val + rValue); 19 } 20 int maxPathSum(TreeNode *root) { 21 int gMax = INT_MIN, lMax = INT_MIN; 22 lMax = getSum(root, gMax); 23 return max(lMax, gMax); 24 } 25 };
LeetCode – Refresh – Binary Tree Maximum Path Sum
标签:
原文地址:http://www.cnblogs.com/shuashuashua/p/4346183.html