-
Notifications
You must be signed in to change notification settings - Fork 9
/
BinaryTreeMaximumPathSum.cpp
37 lines (31 loc) · 1.12 KB
/
BinaryTreeMaximumPathSum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Problem: https://leetcode.com/problems/binary-tree-maximum-path-sum/
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class BinaryTreeMaximumPathSum {
public:
int maxPathSum(TreeNode* root) {
maxSum(root);
return this->_msum;
}
private:
int maxSum(TreeNode* node) {
// Handling the base-case.
if (node == nullptr) return 0;
// Max-sum through children node.
int maxSumLeft = std::max(maxSum(node->left), 0);
int maxSumRight = std::max(maxSum(node->right), 0);
// Calculating the sum through the root-node.
int node_sum = node->val + maxSumLeft + maxSumRight;
if (node_sum > this->_msum) this->_msum = node_sum;
// Returning the sum assuming this node is part of the path.
return node->val + max(maxSumLeft , maxSumRight);
}
int _msum = INT_MIN;
};