百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

LeetCode 力扣官方题解 | 2049. 统计最高分的节点数目

bigegpt 2024-08-19 11:58 2 浏览


2049. 统计最高分的节点数目

题目描述

难易度:中等

给你一棵根节点为 0 的 二叉树 ,它总共有 n 个节点 ,节点编号为 0 到 n - 1 。同时给你一个下标从 0 开始的整数数组 parents 表示这棵树 ,其中 parents[i] 是节点 i 的父节点 。由于节点 0 是根 ,所以 parents [0] == -1 。

一个子树的 大小 为这个子树内节点的数目 。每个节点都有一个与之关联的 分数 。求出某个节点分数的方法是 ,将这个节点和与它相连的边全部 删除 ,剩余部分是若干个 非空 子树 ,这个节点的 分数 为所有这些子树 大小的乘积

请你返回有 最高得分 节点的 数目

示例 1:

输入:parents = [-1,2,0,2,0]
输出:3
解释:
- 节点 0 的分数为:3 * 1 = 3
- 节点 1 的分数为:4 = 4
- 节点 2 的分数为:1 * 1 * 2 = 2
- 节点 3 的分数为:4 = 4
- 节点 4 的分数为:4 = 4
最高得分为 4 ,有三个节点得分为 4 (分别是节点 1,3 和 4 )


示例 2:

输入:parents = [-1,2,0]
输出:2
解释:
- 节点 0 的分数为:2 = 2
- 节点 1 的分数为:2 = 2
- 节点 2 的分数为:1 * 1 = 1
最高分数为 2 ,有两个节点分数为 2 (分别为节点 0 和 1 )。


提示:

  • n == parents.length
  • 2 <= n <= 105
  • parents[0] == -1
  • 对于 i != 0 ,有 0 <= parents[i] <= n - 1
  • parents 表示一棵二叉树。


解决方案

方法一:深度优先搜素


思路

在一棵树中,当把一个节点和与它相连的所有边删除,剩余部分最多为三棵非空子树,即原节点的左子树(如果有),右子树(如果有),以及把以这个节点为根结点的子树移除所形成的子(除根结点外均有)。而这个节点的分数为这些子树的节点个数的乘积。我们可以先用 parents 数组统计出每个节点的子节点,然后使用深度优先搜索来计算以每个节点为根结点的子树的大小,同时计算每个节点的大小,作为深度优先搜索的返回值,最后统计最大分数出现的次数。在实现上,统计最大分数出现的次数可以放到深度优先搜索中完成,从而节省一部分空间。

代码

Python3

class Solution:
    def countHighestScoreNodes(self, parents: List[int]) -> int:
        n = len(parents)
        children = [[] for _ in range(n)]
        for node, p in enumerate(parents):
            if p != -1:
                children[p].append(node)




        maxScore, cnt = 0, 0
        def dfs(node: int) -> int:
            score = 1
            size = n - 1
            for ch in children[node]:
                sz = dfs(ch)
                score *= sz
                size -= sz
            if node != 0:
                score *= size
            nonlocal maxScore, cnt
            if score == maxScore:
                cnt += 1
            elif score > maxScore:
                maxScore, cnt = score, 1
            return n - size
        dfs(0)
        return cnt


Java

class Solution {
    long maxScore = 0;
    int cnt = 0;
    int n;
    List<Integer>[] children;




    public int countHighestScoreNodes(int[] parents) {
        n = parents.length;
        children = new List[n];
        for (int i = 0; i < n; i++) {
            children[i] = new ArrayList<Integer>();
        }
        for (int i = 0; i < n; i++) {
            int p = parents[i];
            if (p != -1) {
                children[p].add(i);
            }
        }
        dfs(0);
        return cnt;
    }




    public int dfs(int node) {
        long score = 1;
        int size = n - 1;
        for (int c : children[node]) {
            int t = dfs(c);
            score *= t;
            size -= t;
        }
        if (node != 0) {
            score *= size;
        }
        if (score == maxScore) {
            cnt++;
        } else if (score > maxScore) {
            maxScore = score;
            cnt = 1;
        }
        return n - size;
    }
}

C#

public class Solution {
    long maxScore = 0;
    int cnt = 0;
    int n;
    IList<int>[] children;




    public int CountHighestScoreNodes(int[] parents) {
        n = parents.Length;
        children = new IList<int>[n];
        for (int i = 0; i < n; i++) {
            children[i] = new List<int>();
        }
        for (int i = 0; i < n; i++) {
            int p = parents[i];
            if (p != -1) {
                children[p].Add(i);
            }
        }
        DFS(0);
        return cnt;
    }




    public int DFS(int node) {
        long score = 1;
        int size = n - 1;
        foreach (int c in children[node]) {
            int t = DFS(c);
            score *= t;
            size -= t;
        }
        if (node != 0) {
            score *= size;
        }
        if (score == maxScore) {
            cnt++;
        } else if (score > maxScore) {
            maxScore = score;
            cnt = 1;
        }
        return n - size;
    }
}


C++

class Solution {
public:
    long maxScore = 0;
    int cnt = 0;
    int n;
    vector<vector<int>> children;




    int dfs(int node) {
        long score = 1;
        int size = n - 1;
        for (int c : children[node]) {
            int t = dfs(c);
            score *= t;
            size -= t;
        }
        if (node != 0) {
            score *= size;
        }
        if (score == maxScore) {
            cnt++;
        } else if (score > maxScore) {
            maxScore = score;
            cnt = 1;
        }
        return n - size;
    }




    int countHighestScoreNodes(vector<int>& parents) {
        this->n = parents.size();
        this->children = vector<vector<int>>(n);
        for (int i = 0; i < n; i++) {
            int p = parents[i];
            if (p != -1) {
                children[p].emplace_back(i);
            }
        }
        dfs(0);
        return cnt;
    }
};


C

int dfs(int node, long * maxScore, int * cnt, int n, const struct ListNode ** children) {
    long score = 1;
    int size = n - 1;
    for (struct ListNode * curr = children[node]; curr; curr = curr->next) {
        int t = dfs(curr->val, maxScore, cnt, n, children);
        score *= t;
        size -= t;
    }
    if (node != 0) {
        score *= size;
    }
    if (score == *maxScore) {
        (*cnt)++;
    } else if (score > *maxScore) {
        *maxScore = score;
        *cnt = 1;
    }
    return n - size;
}




int countHighestScoreNodes(int* parents, int parentsSize){
    int n = parentsSize;
    int cnt = 0;
    long maxScore = 0;
    struct ListNode ** children = (struct ListNode **)malloc(sizeof(struct ListNode *) * n);
    for (int i = 0; i < n; i++) {
        children[i] = NULL;
    }
    for (int i = 0; i < n; i++) {
        int p = parents[i];
        if (p != -1) {
            struct ListNode * node = (struct ListNode *)malloc(sizeof(struct ListNode));
            node->val = i;
            node->next = children[p];
            children[p] = node;
        }
    }
    dfs(0, &maxScore, &cnt, n, children);
    for (int i = 0; i < n; i++) {
        for (struct ListNode * curr = children[i]; curr; ) {
            struct ListNode * next = curr->next;
            free(curr);
            curr = next;
        }
    }
    free(children);
    return cnt;
}


Golang





func countHighestScoreNodes(parents []int) (ans int) {
    n := len(parents)
    children := make([][]int, n)
    for node := 1; node < n; node++ {
        p := parents[node]
        children[p] = append(children[p], node)
    }




    maxScore := 0
    var dfs func(int) int
    dfs = func(node int) int {
        score, size := 1, n-1
        for _, ch := range children[node] {
            sz := dfs(ch)
            score *= sz
            size -= sz
        }
        if node > 0 {
            score *= size
        }
        if score == maxScore {
            ans++
        } else if score > maxScore {
            maxScore = score
            ans = 1
        }
        return n - size
    }
    dfs(0)
    return
}


JavaScript

var countHighestScoreNodes = function(parents) {
    const n = parents.length;
    const children = new Array(n).fill(0);
    let maxScore = 0;
    let cnt = 0;
    for (let i = 0; i < n; i++) {
        children[i] = [];
    }
    for (let i = 0; i < n; i++) {
        const p = parents[i];
        if (p !== -1) {
            children[p].push(i);
        }
    }




    const dfs = (node) => {
        let score = 1;
        let size = n - 1;
        for (const c of children[node]) {
            let t = dfs(c);
            score *= t;
            size -= t;
        }
        if (node !== 0) {
            score *= size;
        }
        if (score === maxScore) {
            cnt++;
        } else if (score > maxScore) {
            maxScore = score;
            cnt = 1;
        }
        return n - size;
    }




    dfs(0);
    return cnt;
};


复杂度分析

  • 时间复杂度:O(n),其中 nn 是树的节点数。预处理,深度优先搜索均消耗 O(n) 时间。
  • 空间复杂度:O(n)。统计每个节点的子节点消耗 O(n) 空间,深度优先搜索的深度最多为 O(n) 空间。


BY /

本文作者:力扣

声明:本文归“力扣”版权所有,如需转载请联系。

相关推荐

悠悠万事,吃饭为大(悠悠万事吃饭为大,什么意思)

新媒体编辑:杜岷赵蕾初审:程秀娟审核:汤小俊审签:周星...

高铁扒门事件升级版!婚宴上‘冲喜’老人团:我们抢的是社会资源

凌晨两点改方案时,突然收到婚庆团队发来的视频——胶东某酒店宴会厅,三个穿大红棉袄的中年妇女跟敢死队似的往前冲,眼瞅着就要扑到新娘的高额钻石项链上。要不是门口小伙及时阻拦,这婚礼造型团队熬了三个月的方案...

微服务架构实战:商家管理后台与sso设计,SSO客户端设计

SSO客户端设计下面通过模块merchant-security对SSO客户端安全认证部分的实现进行封装,以便各个接入SSO的客户端应用进行引用。安全认证的项目管理配置SSO客户端安全认证的项目管理使...

还在为 Spring Boot 配置类加载机制困惑?一文为你彻底解惑

在当今微服务架构盛行、项目复杂度不断攀升的开发环境下,SpringBoot作为Java后端开发的主流框架,无疑是我们手中的得力武器。然而,当我们在享受其自动配置带来的便捷时,是否曾被配置类加载...

Seata源码—6.Seata AT模式的数据源代理二

大纲1.Seata的Resource资源接口源码2.Seata数据源连接池代理的实现源码3.Client向Server发起注册RM的源码4.Client向Server注册RM时的交互源码5.数据源连接...

30分钟了解K8S(30分钟了解微积分)

微服务演进方向o面向分布式设计(Distribution):容器、微服务、API驱动的开发;o面向配置设计(Configuration):一个镜像,多个环境配置;o面向韧性设计(Resista...

SpringBoot条件化配置(@Conditional)全面解析与实战指南

一、条件化配置基础概念1.1什么是条件化配置条件化配置是Spring框架提供的一种基于特定条件来决定是否注册Bean或加载配置的机制。在SpringBoot中,这一机制通过@Conditional...

一招解决所有依赖冲突(克服依赖)

背景介绍最近遇到了这样一个问题,我们有一个jar包common-tool,作为基础工具包,被各个项目在引用。突然某一天发现日志很多报错。一看是NoSuchMethodError,意思是Dis...

你读过Mybatis的源码?说说它用到了几种设计模式

学习设计模式时,很多人都有类似的困扰——明明概念背得滚瓜烂熟,一到写代码就完全想不起来怎么用。就像学了一堆游泳技巧,却从没下过水实践,很难真正掌握。其实理解一个知识点,就像看立体模型,单角度观察总...

golang对接阿里云私有Bucket上传图片、授权访问图片

1、为什么要设置私有bucket公共读写:互联网上任何用户都可以对该Bucket内的文件进行访问,并且向该Bucket写入数据。这有可能造成您数据的外泄以及费用激增,若被人恶意写入违法信息还可...

spring中的资源的加载(spring加载原理)

最近在网上看到有人问@ContextConfiguration("classpath:/bean.xml")中除了classpath这种还有其他的写法么,看他的意思是想从本地文件...

Android资源使用(android资源文件)

Android资源管理机制在Android的开发中,需要使用到各式各样的资源,这些资源往往是一些静态资源,比如位图,颜色,布局定义,用户界面使用到的字符串,动画等。这些资源统统放在项目的res/独立子...

如何深度理解mybatis?(如何深度理解康乐服务质量管理的5个维度)

深度自定义mybatis回顾mybatis的操作的核心步骤编写核心类SqlSessionFacotryBuild进行解析配置文件深度分析解析SqlSessionFacotryBuild干的核心工作编写...

@Autowired与@Resource原理知识点详解

springIOCAOP的不多做赘述了,说下IOC:SpringIOC解决的是对象管理和对象依赖的问题,IOC容器可以理解为一个对象工厂,我们都把该对象交给工厂,工厂管理这些对象的创建以及依赖关系...

java的redis连接工具篇(java redis client)

在Java里,有不少用于连接Redis的工具,下面为你介绍一些主流的工具及其特点:JedisJedis是Redis官方推荐的Java连接工具,它提供了全面的Redis命令支持,且...