[leetcode] 2049 统计最高分的节点数目 | dfs二叉树

题目链接
在这里插入图片描述
记录父亲节点的深度优先遍历不经常写,然后把给出的数据改成记录子节点,然后对根进行 d f s dfs dfs,记录以当前节点为根的结点的数量,然后枚举删除某个节点的情况下的分数是多少{
需要讨论当前节点是否为根
}
然后统计最大值并记录个数

Code:

class Solution {
public:
    int cnt[100000 + 1];
    vector<int> son[100000 + 1];
    int countHighestScoreNodes(vector<int> &parents) {
        const int siz = parents.size();
        if (siz == 2) return 2;
        memset(cnt, 0, sizeof cnt);
        int root;
        for (int i = 0; i < siz; i++) {
            int fa = parents[i];
            if (fa == -1) {
                root = i;
                continue;
            }
            son[fa].push_back(i);
        }
        cnt[root] = dfs(root);
        long long mx = 0, ret = 0;
        for (int i = 0; i < siz; i++) {
            if (root == i) {
                long long tmx = 1;
                for (int x: son[i]) tmx *= cnt[x];
                if (tmx < mx) continue;
                else if (tmx == mx) ret++;
                else {
                    mx = tmx;
                    ret = 1;
                }
            } else {
                long long tmx = 1;
                for (int x: son[i]) tmx *= cnt[x];
                tmx *= siz - cnt[i];
                if (tmx < mx) continue;
                else if (tmx == mx) ret++;
                else {
                    mx = tmx;
                    ret = 1;
                }
            }
            // cout << i << "   " << mx << endl;
        }
        return ret;
    }

    int dfs(int root) {
        int sum = 0;
        for (int i = 0; i < son[root].size(); i++) {
            int u = son[root][i];
            cnt[u] = dfs(u);
            sum += cnt[u];
        }
        return sum + 1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值