leetcode 310. Minimum Height Trees(最小高度树)

论文翻译:2024 High-Confidence Computing A survey on large language model (LLM) security and privacy: The 大型语言模型(LLMs),如ChatGPT和Bard,已经彻底改变了自然语言理解和生成。它们具有深度语言理解能力、类似人类的文本生成能力、上下文意识和强大的问题解决技能,使它们在各个领域(例如搜索引擎、客户支持、翻译)中变得不可或缺。同时,LLMs也在安全领域获得了关注,揭示了安全漏洞并展示了它们在安全相关任务中的潜力。本文探讨了LLMs与安全性和隐私的交集。具体来说,我们研究了LLMs如何积极影响安全性和隐私,与它们使用相关的潜在风险和威胁,以及LLMs内部的固有漏洞。 阅读详情

A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.

Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h)) are called minimum height trees (MHTs).

Return a list of all MHTs’ root labels. You can return the answer in any order.

The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
在这里插入图片描述
一个无向图表示的树,有n个节点(0到n-1),边edges = [ai, bi]表示第i条边的两个端点是ai, bi。
选任一节点作为root, 可得到一个树的高度。
返回可以得到最小高度的所有root

思路:
可以用拓扑排序,先介绍下拓扑排序。参考链接
在这里插入图片描述
这里同样选一个入度为0的node,一层一层删掉,最后剩<=2个node时结束,剩下的node就是我们需要的root

为什么要这样做?因为每次删掉的都是入度为0(最外层)的node,剩下的是处于最中间的node
为什么要选剩下的<=2个节点?剩一个节点时,它肯定是最中间的root。剩两个时,两个谁做root,高度都是一样的。当剩3个时,由于树中不存在环,肯定有一个高度是大于另外两个的。

具体实现步骤:

  1. 将输入的边edges构建成图,注意无向图要双向
  2. 找到入度为0(即仅有一个边)的node,放入queue
  3. 由于是无向图,需要从边的另一端点对应的连接node表中,删除当前node,删除完后,如果只剩下一个边,装入queue,作为下一轮删除对象
  4. 直到queue中只剩下<=2个节点,返回
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> roots = new ArrayList<>();
        if(n == 0 || edges == null) return roots;
        
        if(n == 1) {
            roots.add(0);
            return roots;
        }
        if(n == 2) {
            roots.add(0);
            roots.add(1);
            return roots;
        }
        
        //HashSet便于删除node
        List<Set<Integer>> graph = new ArrayList<>(n);
        
        for(int i = 0; i < n; i++) {
            graph.add(new HashSet<Integer>());
        }
        
        //无向图
        for(int[] edge : edges) {
            graph.get(edge[0]).add(edge[1]);
            graph.get(edge[1]).add(edge[0]);
        }
        
        for(int i = 0; i < n; i++) {
            if(graph.get(i).size() == 1) {
                roots.add(i);
            }
        }
        
        while(n > 2) {
            n -= roots.size();  //遍历下来roots里面的节点都要删除
            List<Integer> newRoots = new ArrayList<>(); //保存新的叶子节点
            for(Integer root : roots) {
                int node = graph.get(root).iterator().next();
                graph.get(node).remove(root);
                if(graph.get(node).size() == 1) newRoots.add(node);
            }
            roots = newRoots;
        }
        return roots;
        
    }

上面的方法有点耗时,主要是在于要从边的另一端点所对应的表中删除当前node。其实我们想要的只是看入度是否为0(是否只有一条边),即边的另一端点所对应的表的size是否为1。并不关心每个点具体和哪个点相连接。

可以建立一个数组,记录每个node有几条边,当只有一条边时加入queue,就不需要再反复地删除节点了。

以下是错误做法,因为如果没有新添加入度为0的节点,而queue中的节点仅剩两个的时候,就会跳出循环,queue中保存的之前的节点会处理不完

while(queue.size() > 2) {
            int deleteNode = queue.poll();
            //由于没有节点删除这一步了,要遍历整个连接点的表
            int deleteConnectNode = graph[deleteNode].get(0); //入度为0,肯定只连接一个点
            degree[deleteNode] --;
            degree[deleteConnectNode] --;
            if(degree[deleteConnectNode] == 1) queue.offer(deleteConnectNode);
        }

完整代码

    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> roots = new ArrayList<>();
        if(n == 0 || edges == null) return roots;
        
        if(n == 1) {
            roots.add(0);
            return roots;
        }
        if(n == 2) {
            roots.add(0);
            roots.add(1);
            return roots;
        }
        
        ArrayList<Integer>[] graph = new ArrayList[n];
        int[] degree = new int[n];
        Queue<Integer> queue = new LinkedList<Integer>();
        boolean[] removed = new boolean[n];
        
        for(int i = 0; i < n; i++) {
            graph[i] = new ArrayList<Integer>();
        }
        
        
        for(int[] edge : edges) {
            graph[edge[0]].add(edge[1]);
            graph[edge[1]].add(edge[0]);
            degree[edge[0]] ++;
            degree[edge[1]] ++;
        }
        
        for(int i = 0; i < n; i++) {
            if(degree[i] == 1) queue.offer(i); 
        }
        
        while(n > 2) {
            int size = queue.size();
            n -= size;
            while(size > 0) {
                int deleteNode = queue.poll();
                removed[deleteNode] = true;
                for(int deleteConnectNode : graph[deleteNode]) {
                    if(removed[deleteConnectNode]) continue;
                    degree[deleteConnectNode] --;
                    if(degree[deleteConnectNode] == 1) queue.offer(deleteConnectNode);
                }
                size --;
            }
        }
        
        roots.addAll(queue);
        return roots;
    }
win7 vs2012+wdk8.0 搭建wdf驱动开发环境 开发环境搭建: 系统:win7 x64 工具:vs2012 + WDK8.0 插件:wdfcoinstaller.msi (1)先安装vs2012,再安装wdk8.0,这样在打开vs2012时可以创建windows drivers类型的工程。 注:vs2012不能安装wdk8.1,wdk8.1必须安装在vs2013上 下载链接:http://msdn.microsoft.com/zh-cn/win... 阅读详情

相关推荐

基于FPGA的DDS信号发生器

之前的博客讲到了DDS的基本原理,现在用Verilog代码实现DDS,能够产生四种波形,方波,三角波,正弦波,锯齿波,用按键来控制频率和选择波形。其中按键消抖模块来自小梅哥的FPGA自学笔记设计与验证这本书。 module DDS_Module( Clk, Rst_n, EN, Fword, Key1, Pword, DA_Clk, DA_Data ); input Clk...

qq_43534451的博客 9959

最小高度树

力扣算法之最小高度树

qq_52916408的博客 1178

Cadence IC618/Spectre231安装避坑指南:详解License配置、环境变量隔离与依赖检查

本文详细介绍了Cadence IC618/Spectre231的安装与配置避坑指南,包括许可证系统精妙控制、环境隔离模块化实践、依赖管理进阶技巧以及长期维护的黄金法则。通过实战案例和解决方案,帮助工程师构建稳定可靠的EDA工作环境,提升芯片设计效率。

weixin_28683065的博客 487

LeetCode-310. 最小高度树【dfs,bfs,拓扑排序】

LeetCode-310. 最小高度树【dfs,bfs,拓扑排序】

zik的博客 766

《YOLOv8实例分割实战:训练自己的数据集 》(视频课程)

本课程将手把手地教大家使用labelme标注和使用YOLOv8训练自己的数据集,完成一个多目标实例分割实战项目。

bai666ai的博客 795

Windows 10下用Python 3搞定Android源码下载:最新repo工具避坑指南

本文详细介绍了在Windows 10系统上,使用Python 3和官方最新repo工具下载Android源码的完整流程。文章提供了从Git安装、环境配置到repo工具初始化、同步加速及常见错误排查的避坑指南,帮助开发者高效搭建稳定的源码下载环境。

weixin_29266749的博客 443

310. Minimum Height Trees

本题给出一个有树性质的无向图,可以选择任何一个点做树根,要求在所有可能性中,找出树高最小的MHTs,并输出树根。 本题给出的图本身就是一棵树,不是一个最小生成树的问题。理论上求出每个节点对应的树高,然后排序即可,这样的复杂度在O(v*v),没有试过这样能不能过。 另一方面,也可以将问题转化来看,首先,先不考虑两个节点以下的情况,很显然图中入度为0的点形成的树一定不是MHTs;入度为1的点也不是,

zdinanyang的博客 450

GEE实战:基于Modis NPP数据的全球植被生产力动态监测与分析

本文详细介绍了如何利用Google Earth Engine(GEE)平台和Modis NPP数据,进行全球植被生产力的动态监测与分析。通过实战代码演示,涵盖数据加载、区域统计、年际趋势计算及空间制图等核心步骤,为生态评估与气候变化研究提供了一套高效的数据分析解决方案。

weixin_29197699的博客 558

力扣 310. 最小高度树

题目 树是一个无向图,其中任何两个顶点只通过一条路径连接。 换句话说,一个任何没有简单环路的连通图都是一棵树。 给你一棵包含 n 个节点的树,标记为 0 到 n - 1 。给定数字 n 和一个有 n - 1 条无向边的 edges 列表(每一个边都是一对标签),其中 edges[i] = [ai, bi] 表示树中节点 ai 和 bi 之间存在一条无向边。 可选择树中任何一个节点作为根。当选择节点 x 作为根节点时,设结果树的高度为 h 。在所有可能的树中,具有最小高度的树(即,min(h))被称为 最小高

(ง •_•)ง没有困难的工作,只有勇敢的狗狗 818

大唐杯历届省赛押题训练(6)

考试-TD-LTE无线网络设备介绍-TD-LTE网络架构一、单选题1TD-LTE的接入网E-UTRAN由下列哪些网元组成( )。0分/1分A、RNCB、BTSC、eNode BD、Node B提交答案:B正确答案:C考点TD-LTE网络架构解析暂无试题解析二、多选题1关于LTE网络整体结构,哪些说法是正确的( )0分/2分A、E-UTRAN用E-NodeB替代原有的RNC-NodeB结构B、E-NodeB间的接口为S1接口C、各网络节点之间的接口使用IP传输。

nimo观察者 646

[QMT量化交易小白入门]-七十三、主力资金动向:板块与个股资金流数据API(量化python代码解析)

本专栏主要是介绍QMT的基础用法,常见函数,写策略的方法,也会分享一些量化交易的思路,大概会写100篇左右。QMT的相关资料较少,在使用过程中不断的摸索,遇到了一些问题,记录下来和大家一起沟通,共同进步。

木头大左的博客 1136

LeetCode 310. Minimum Height Trees(最小高度树)

原题网址:https://leetcode.com/problems/minimum-height-trees/ For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all po

James Pan 3128

YOLOv8改进 | 注意力机制 | 添加DAttention (DAT)注意力机制实现极限涨点

本文给大家带来的是YOLOv8改进DAT的教程,其发布于2022年CVPR2022上同时被评选为Best Paper,由此可以证明其是一种十分有效的改进机制,其主要的核心思想是:引入可变形注意力机制和动态采样点(听着是不是和可变形动态卷积DCN挺相似)。同时在网络结构中引入一个DAT计算量由8.9GFLOPs涨到了9.4GFLOPs。本文的讲解主要包含三方面:DAT的网络结构思想、DAttention的代码复现,如何添加DAttention到你的结构中实现涨点,下面先来分享我测试的对比图。

Snu77的博客 1万+

Leetcode310. Minimum Height Trees最小高度树

对于一个具有树特征的无向图,我们可选择任何一个节点作为根。图因此可以成为树,在所有可能的树中,具有最小高度的树被称为最小高度树。给出这样的一个图,写出一个函数找到所有的最小高度树并返回他们的根节点。 格式 该图包含n个节点,标记为0到n - 1。给定数字n和一个无向边edges列表(每一个边都是一对标签)。 你可以假设没有重复的边会出现在edges中。由于所有的边都是无...

lMonster81 385

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

[Swift]LeetCode310. 最小高度树 | Minimum Height Trees

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)➤GitHub地址:https://github.com/strengthen/LeetCode➤原文地址:https://www.cnblogs.com/streng...

weixin_30906425的博客 179

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

【LeetCode】310. Minimum Height Trees 最小高度树(Medium)(JAVA)

【LeetCode】310. Minimum Height Trees 最小高度树(Medium)(JAVA) 题目地址: https://leetcode.com/problems/minimum-height-trees/ 题目描述: A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph

qq_16927853的博客 287

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

leetcode 310. Minimum Height Trees 最小高度树(中等)

leetcode 310. Minimum Height Trees 最小高度树(中等)

ln_ydc的专栏 188

leetcode 310. Minimum Height Trees | 310. 最小高度树(图的邻接矩阵DFS / 拓扑排序)

题目 https://leetcode.com/problems/minimum-height-trees/ 题解 方法1:图的邻接矩阵 DFS(超时) 我一想,这不就是个图嘛,于是随手敲出一个 DFS,结果。。超时了。 class Vertex { Integer val; List<Integer> next; public Vertex() { next = new LinkedList<>(); } } class Sol

寒泉 5万+

[LeetCode] 310. Minimum Height Trees 最小高度树

For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called mini...

weixin_30898109的博客 130

【leetcode_310】【中等】minimum-height-trees / 最小高度树

拓扑排序 无向图 degree自减

过得精彩,无所谓好坏 843

leetcode 310. Minimum Height Trees 图的构建+最小高度树+DFS深度优先遍历+拓扑排序

For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called mini...

JackZhangNJU的专栏 1174

LeetCode C++ 310. Minimum Height Trees【Graph/BFS/拓扑排序】中等

Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Note: Each element in the result must be unique. The re

memcpy0的博客 635

LeetCode //C - 310. Minimum Height Trees

【代码】LeetCode //C - 310. Minimum Height Trees。

Made in Code 1248

[LeetCode 310] Minimum Height Trees

For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called mini

coder 进阶的专栏 4539

【LEETCODE】310-Minimum Height Trees

For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called mini

aliceyangxi1987的博客 2057

Leetcode 310. Minimum Height Trees(python)

Leetcode 310. Minimum Height Trees题目解法:拓扑排序+BFS 题目 For an undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible roo...

qq_37821701的博客 506
上一篇: leetcode 147. Insertion Sort List (链表插入排序)
下一篇: leetcode 878. Nth Magical Number (第N个魔法数)
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址