LeetCode 124. Binary Tree Maximum Path Sum
参考链接:http://zxi.mytechroad.com/blog/tree/leetcode-124-binary-tree-maximum-path-sum/
Solution1:
Time complexity
Space complexity
代码如下:
花花酱讲的就是好啊!
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxPathSum(TreeNode* root) {
if (!root) return 0;
int ans = INT_MIN;
my_PathSum(root, ans);//ans保存了在递归过程中的最大值,
return ans; //而此函数的返回值是经过根结点的最大路径和,经过根结点的未必是整体最大的故该返回值无用
}
int my_PathSum(TreeNode* root, int &ans) {
if (!root) return 0;
int l = max(0, my_PathSum(root->left, ans));
int r = max(0, my_PathSum(root->right, ans));
int sum = l + r + root->val;
ans = max(ans, sum);//ans保存着经过当前root结点时的最大路径和
return root->val + max(l, r);//返回单边值
}
};