LeetCode(124) Binary Tree Maximum Path Sum (如何递归?)

来源:互联网 发布:www.杭州行知小学.com 编辑:程序博客网 时间:2024/06/06 20:05

转载 :http://blog.csdn.net/fly_yr/article/details/50412751

ac代码

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int INF = 0x7fffffff;    int MIN_INF = -INF-1;    int maxVal;    int dfs(TreeNode* root)    {        if(root == NULL)            return 0;        else{            int leftM = dfs(root->left);            int rightM = dfs(root->right);            int rootVal = root->val;            int cur = rootVal;            if(leftM > 0)                cur += leftM;            if(rightM > 0)                cur += rightM;            if(cur > maxVal)                maxVal = cur;            return max(rootVal, max(rootVal+leftM, rootVal+rightM));        }    }    int maxPathSum(TreeNode* root) {        if(root == NULL)                return 0;        maxVal = MIN_INF;        dfs(root);        return maxVal;    }};

注意递归思路

0 0
原创粉丝点击