forked from iphkwan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_Tree_Maximum_Path_Sum.cc
39 lines (39 loc) · 1.2 KB
/
Binary_Tree_Maximum_Path_Sum.cc
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
/**
* 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 dfs (TreeNode *rt, int &ans) {
ans = max(ans, rt->val);
if (rt->left == NULL && rt->right == NULL)
return rt->val;
if (rt->left != NULL && rt->right == NULL) {
int tmp = rt->val + dfs(rt->left, ans);
ans = max(ans, tmp);
return max(rt->val, tmp);
}
if (rt->left == NULL && rt->right != NULL) {
int tmp = rt->val + dfs(rt->right, ans);
ans = max(ans, tmp);
return max(rt->val, tmp);
}
int tmp1 = dfs(rt->left, ans);
int tmp2 = dfs(rt->right, ans);
ans = max(ans, rt->val + max(tmp1, tmp2));
ans = max(ans, rt->val + tmp1 + tmp2);
return max(rt->val, rt->val + max(tmp1, tmp2));
}
int maxPathSum(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int ans = -0x7ffffff;
dfs(root, ans);
return ans;
}
};