[Leetcode] Max Tree Sum

来源:互联网 发布:销售出入库软件 编辑:程序博客网 时间:2024/06/05 22:32

不多说了~


/** * 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) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(!root){            return 0;        }        int maxSumVal = INT_MIN;        currentMaxValue(root,maxSumVal);        return maxSumVal;    }            int currentMaxValue (TreeNode *root,int& sum) {                if(!root){            return 0;        }                int rootSelf = root->val;        int rootLeft = currentMaxValue(root->left,sum);        int rootRight = currentMaxValue(root->right,sum);        int rootLeft2right = rootLeft + rootRight  + rootSelf;        int localMaxVal = max(max(rootLeft+rootSelf,rootRight+rootSelft),max(rootLeft+rootSelf,rootSelf));        sum = max(max(sum,localMaxVal),max(sum,rootLeft2right));        return localMaxVal;    }};


原创粉丝点击