forked from leetcoders/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTreeMaximumPathSum.h
47 lines (44 loc) · 1.09 KB
/
BinaryTreeMaximumPathSum.h
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
/*
Author: Annie Kim, [email protected] : King, [email protected]
Date: Apr 28, 2013
Update: Oct 07, 2014
Problem: Binary Tree Maximum Path Sum
Difficulty: Easy
Source: http://leetcode.com/onlinejudge#question_124
Notes:
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.
Solution: Recursion...
*/
/**
* 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 res = INT_MIN;
maxPathSumRe(root, res);
return res;
}
int maxPathSumRe(TreeNode *node, int &res)
{
if (!node) return 0;
int l = maxPathSumRe(node->left, res);
int r = maxPathSumRe(node->right, res);
int sum = max(node->val, max(l, r) + node->val);
res = max(res, max(0, l) + max(0, r) + node->val);
return sum;
}
};