[leetcode]Binary Tree Maximum Path Sum

来源:互联网 发布:域名备案系统 编辑:程序博客网 时间:2024/06/14 10:21
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void dfs(TreeNode *root, int &sum, int &result) {
        if (root == NULL) {
            sum = 0;
            return;
        }
        int s1, s2;
        dfs(root->left, s1, result);
        dfs(root->right, s2, result);
        sum = max(root->val, max(root->val + s1, root->val + s2));
        int tot = root->val;
        if (s1 > 0) tot += s1;
        if (s2 > 0) tot += s2;
        if (tot > result) result = tot;
    }
    int maxPathSum(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int result = INT_MIN;
        int sum;
        dfs(root, sum, result);
        return result;
    }
};