Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3] 1 / \ 2 3 Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \ 15 7 Output: 42
/**
* 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) {
int ans = INT_MIN;
int sumWithRoot = helper(root, ans);
return ans != INT_MIN ? ans : 0;
}
int helper(TreeNode *root, int& ans) {
if (root == NULL) {
return 0;
}
int leftSum = helper(root -> left, ans);
int rightSum = helper(root -> right, ans);
int sumWithRoot = root -> val;
if (leftSum > 0) {
sumWithRoot += leftSum;
}
if (rightSum > 0) {
sumWithRoot += rightSum;
}
ans = max(ans, sumWithRoot);
if (max(leftSum, rightSum) > 0) {
return max(leftSum, rightSum) + root -> val;
} else {
return root -> val;
}
}
};
===========
class Solution {
public:
int maxPathSum(TreeNode* root) {
int ans = INT_MIN;
helper(root, ans);
return ans;
}
int helper(TreeNode* root, int& ans) {
if (root == NULL) {
return 0;
}
int left_sum = helper(root -> left, ans);
int right_sum = helper(root -> right, ans);
ans = max(ans, left_sum + right_sum + root -> val);
int sum = (left_sum > right_sum ? left_sum : right_sum) + root -> val;
return sum > 0 ? sum : 0;
}
};
No comments:
Post a Comment