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

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

int maxPathSum(TreeNode *n, int &max) {
    if (n == NULL) return 0;

    int lSum = maxPathSum(n->left, max);
    int rSum = maxPathSum(n->right, max);

    int sum = n->val; // sum for node as root
    int pathSum = 0;  // sum for node as child node
    if (lSum > 0) {
        sum += lSum;
        pathSum += lSum;
    }

    if (rSum > 0) {
        sum += rSum;
        if (pathSum < rSum) {
            pathSum = rSum;
        }
    }
    
    if (sum > max) max = sum;

    pathSum += n->val;
    return pathSum;
}


int maxPathSum(TreeNode *root) {
    int max = INT_MIN;
    maxPathSum(root, max);
    return max;
}
View Program Text


Test Status