LeetCode – Refresh – Binary Tree Maximum Path Sum
2015-03-18 08:06
441 查看
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.
Use gMax get the maximum value of the whole sub branch (include current node). So gMax need to pass by reference.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int getSum(TreeNode *root, int &gMax) { if (!root) return 0; int lValue = getSum(root->left, gMax), rValue = getSum(root->right, gMax), total = root->val; total += lValue > 0 ? lValue : 0; total += rValue > 0 ? rValue : 0; gMax = max(total, gMax); return max(max(root->val, root->val + lValue), root->val + rValue); } int maxPathSum(TreeNode *root) { int gMax = INT_MIN, lMax = INT_MIN; lMax = getSum(root, gMax); return max(lMax, gMax); } };
相关文章推荐
- 【LeetCode】Binary Tree Maximum Path Sum
- 【leetcode】binary tree maximum path sum
- [LeetCode 124] Binary Tree Maximum Path Sum (DFS/二叉树)
- [leetcode]Binary Tree Maximum Path Sum
- LeetCode 124:Binary Tree Maximum Path Sum
- LeetCode124—Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum leetcode java
- [LeetCode] Binary Tree Maximum Path Sum Solution
- [LeetCode] Binary Tree Maximum Path Sum
- 【leetcode】Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- LeetCode 124: Binary Tree Maximum Path Sum
- 【leetcode】Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- [leetcode]Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- leetcode Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum
- Leetcode——binary-tree-maximum-path-sum
- Leetcode: Binary Tree Maximum Path Sum