-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtreeMaxPathSum
More file actions
48 lines (39 loc) · 893 Bytes
/
Copy pathtreeMaxPathSum
File metadata and controls
48 lines (39 loc) · 893 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1
/ \
2 3
Return 6.
*/
/**
* 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 maxSum;
int dfs(TreeNode *root){
if (root==NULL) return 0;
int l = dfs(root->left);
int r = dfs(root->right);
int v = root->val;
if (l>0) v+=l;
if (r>0) v+=r;
maxSum = max(maxSum,v);
if (max(l,r)>0) return (max(l,r)+root->val);
else return root->val;
}
int maxPathSum(TreeNode *root) {
maxSum = INT_MIN;
dfs(root);
return maxSum;
}
};