forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-tree-maximum-path-sum.cpp
47 lines (42 loc) · 1.15 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
// 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) {
maxPathSumRecu(root);
return max_sum_;
}
// Return max height and update max path sum for each node.
int maxPathSumRecu(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.
int left = max(0, maxPathSumRecu(root->left));
int right = max(0, maxPathSumRecu(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_ = INT_MIN;
};