forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeMaximumPathSum.cpp
More file actions
33 lines (32 loc) · 1007 Bytes
/
BinaryTreeMaximumPathSum.cpp
File metadata and controls
33 lines (32 loc) · 1007 Bytes
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
/**
* Definition for binary tree
* 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 maxSumGlobal = INT_MIN;
int maxSumCur = 0;
maxPathSum(root, maxSumGlobal, maxSumCur);
return maxSumGlobal;
}
void maxPathSum(TreeNode *root, int& maxSumGlobal, int& maxSumCur) {
if(root==NULL) {
maxSumCur = 0;
return;
}
int maxSumCurLeft = 0;
maxPathSum(root->left, maxSumGlobal, maxSumCurLeft);
int maxSumCurRight = 0;
maxPathSum(root->right, maxSumGlobal, maxSumCurRight);
maxSumCur = max(maxSumCurLeft, maxSumCurRight) + root->val;
maxSumCur = max(maxSumCur, root->val);
maxSumGlobal = max(maxSumGlobal, maxSumCur);
maxSumGlobal = max(maxSumGlobal, maxSumCurLeft+ maxSumCurRight+ root->val);
}
};