Binary Tree Maximum Path Sum
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
Given the below binary tree,
1
/ \
2 3
Return
6.Time Complexity: O(n)
/**
* 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 maxPathSum(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!root) return 0;
int m = root->val;
int localMax = _max(root, m);
return localMax > m ? localMax : m;
}
int _max(TreeNode *root, int &m) {
if (!root) return 0;
int leftMax = _max(root->left, m);
int rightMax = _max(root->right, m);
int maxSum = max(root->val, max(root->val + leftMax, root->val + rightMax));
m = max(max(m, maxSum), root->val + leftMax + rightMax);
return maxSum;
}
};
No comments:
Post a Comment