题解 | #农场最大产奶牛群#

农场最大产奶牛群

https://www.nowcoder.com/practice/16d827f124e14e05b988f3002e7cd651

/**
 * struct TreeNode {
 *  int val;
 *  struct TreeNode *left;
 *  struct TreeNode *right;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param root TreeNode类
 * @return int整型
 */
#include <stdio.h>
void getMaxResult(struct TreeNode* root, int sum, int* max) {
    if (!root) return;
    if (root->left == NULL && root->right == NULL) {
        sum += root->val;
        (*max) = fmax((*max), sum);
    }
    getMaxResult(root->left, sum + root->val, max);
    getMaxResult(root->right, sum + root->val, max);
}
int  dfs(struct TreeNode* root) {
    if (!root) return 0;
    int left = 0, right = 0;
    getMaxResult(root->left, 0, &left);
    getMaxResult(root->right, 0, &right);
    return root->val + left + right;
}
void get(struct TreeNode* root, int* max) {
    if (!root) return;
    int num = dfs(root);
    (*max) = fmax((*max), num);
    get(root->left, max);
    get(root->right, max);
}
int maxMilkSum(struct TreeNode* root ) {
    int max = -1;
    get(root, &max);
    return max;
}

全部评论

相关推荐

03-31 17:40
已编辑
门头沟学院 算法工程师
程序员牛肉:小牛肉来也! 也不要焦虑啦,你第一志愿还没有结束,只是回到人才库(泡大池子等待各个部门挑选)而已。仅仅代表你不符合这个组的用人标准,并不能够说明你在本次暑期实习中没机会加入美团了。 还是平复好心态,不断的复盘,等待下一次面试就好了。
点赞 评论 收藏
分享
03-03 10:35
3d人士会梦见住进比弗利山庄吗:这四个项目属于是初学者的玩具了。不知道面试官咋问,而且双非本搞算法除了9,还是保守至少c9
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务