forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-tree-maximum-path-sum(AC).cpp
57 lines (55 loc) · 1.26 KB
/
binary-tree-maximum-path-sum(AC).cpp
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
#include <algorithm>
#include <climits>
#include <unordered_map>
using namespace std;
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxPathSum(TreeNode *root) {
ans = INT_MIN;
um.clear();
if (root == NULL) {
return ans;
}
um[NULL] = 0;
singlePath(root);
doublePath(root);
return ans;
}
private:
int ans;
unordered_map<TreeNode *, int> um;
void singlePath(TreeNode *root) {
if (root == NULL) {
return;
}
singlePath(root->left);
singlePath(root->right);
um[root] = max(um[root->left], um[root->right]) + root->val;
um[root] = max(um[root], root->val);
}
void doublePath(TreeNode *root) {
if (root == NULL) {
return;
}
ans = max(ans, um[root->left] + um[root->right] + root->val);
ans = max(ans, root->val);
doublePath(root->left);
doublePath(root->right);
}
};