-
Notifications
You must be signed in to change notification settings - Fork 257
/
binary-tree-maximum-path-sum.cpp
48 lines (42 loc) · 1.19 KB
/
binary-tree-maximum-path-sum.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
38
39
40
41
42
43
44
45
46
47
48
// Time: O(n)
// Space: O(h)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxPathSum(TreeNode *root) {
maxPathSumHelper(root);
return max_sum_;
}
// Return max height and update max path sum for each node.
int maxPathSumHelper(TreeNode *root) {
if (root == nullptr) {
return 0;
}
// Get max descendant sum of children.
// If the sum is less than zero, it can't be the path with max sum.
const auto left = max(0, maxPathSumHelper(root->left));
const auto right = max(0, maxPathSumHelper(root->right));
// "max path sum" equals to:
// "max left descendant sum" -> root -> "max right descendant sum".
max_sum_ = max(max_sum_, root->val + left + right);
// Return max descendant sum.
return root->val + max(left, right);
}
private:
int max_sum_ = numeric_limits<int>::min();
};