-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeMaximumPathSum.h
More file actions
59 lines (48 loc) · 1.18 KB
/
BinaryTreeMaximumPathSum.h
File metadata and controls
59 lines (48 loc) · 1.18 KB
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
51
52
53
54
55
56
57
58
59
/**************************************
* Author : luoshikai
* Version : 1.0
* Date : 2013-11-04
* Email : [email protected]
*************************************/
/**************************************
* 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 {
private:
int res;
public:
int maxPathSum(TreeNode *root)
{
res = INT_MIN;
return max(res, maxPathSumRe(root));
}
int maxPathSumRe(TreeNode *node)
{
if (node == NULL) return 0;
int left = maxPathSumRe(node->left);
int right = maxPathSumRe(node->right);
int sum = max(node->val, max(left, right)+node->val);
res = max(res, sum);
res = max(res, node->val+left+right);
return sum;
}
};