题解 | #农场最大产奶牛群#
农场最大产奶牛群
https://www.nowcoder.com/practice/16d827f124e14e05b988f3002e7cd651
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ int pathmax(TreeNode* root, int& sum) { if (root == nullptr) return 0; int left = pathmax(root->left, sum); int right = pathmax(root->right, sum); int path = left + right + root->val; sum = max(sum, path); return max(left, right) + root->val; } int maxMilkSum(TreeNode* root) { // write code here int sum = 0; pathmax(root, sum); return sum; } };