-
Notifications
You must be signed in to change notification settings - Fork 3
/
maxPathSum.cpp
50 lines (46 loc) · 1.02 KB
/
maxPathSum.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
49
50
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
private:
int rootToAny(TreeNode * root)
{
if(root == NULL)
{
return 0;
}
int left = rootToAny(root->left);
int right = rootToAny(root->right);
return max(0,
root->val + max(left, right));
}
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxPathSum(TreeNode *root) {
// write your code here
if(root == NULL)
{
return numeric_limits<int>::min();
}
int leftMax = maxPathSum(root->left);
int rightMax = maxPathSum(root->right);
int maxPath = max(leftMax, rightMax);
int leftSP = rootToAny(root->left);
int rightSP = rootToAny(root->right);
maxPath = max(maxPath,
leftSP + rightSP + root->val);
return maxPath;
}
};