LeetCode:310. Minimum Height Trees

OpenSSL玩转证书链:从Windows CA根证书到签发多域名/IP的服务器证书全攻略 本文详细介绍了如何使用OpenSSL在Windows环境下构建私有CA体系,从创建CA根证书到签发支持多域名/IP的服务器证书的全流程。通过实战指南,读者可以掌握零成本证书管理技术,灵活配置SAN扩展,并了解在Nginx、Apache等主流服务器中的证书部署方法,适用于企业内网、IoT设备等HTTPS加密场景。 阅读详情

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 minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.

    • Format

    1. The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels).

    2. You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.

    • Example 1 :

      Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]]
      
              0
              |
              1
             / \
            2   3 
      
      Output: [1]
      
    • Example 2 :

      Input: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
      
           0  1  2
            \ | /
              3
              |
              4
              |
              5 
      
      Output: [3, 4]
      
    • Note:

      • According to the definition of tree on Wikipedia: “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.”
      • The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
  • 解题思路

    • 解法1 - 暴力破解(超时,Failed)

      • 步骤
        • 以每个节点都为根,对每个节点使用BFS遍历得到以该节点为根时树的高度
        • 比较各个节点时树的高度,得到Minimum Height Trees的根节点
      • 代码
        class Solution {
        public:
            vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
        	vector<int> v;
        	int edgesArray[n][n];
        
                int height[n];
        
                for(int i = 0; i < n; ++i) {
                    height[i] = getHeight(n, i, edges);
                }
        
                // 寻找最小高度树的根节点
                int min = n;
        	for(int i = 0; i < n; ++i) {
        		if(height[i] < min) {
                    min = height[i];
        			v.clear();
        			v.push_back(i);
        		}
        		else if(height[i] == min) {
        			v.push_back(i);
        		}
        	}
        	return v;
            }
        
            // bfs遍历
            int getHeight(int n, int root, vector<pair<int, int> >& edges) {
            	int h = 0;
                int visited[n] = {0};
                visited[root] = 1;
            	queue<int> q;
            	q.push(root);
            	int depth[n] = {0};
            	while(!q.empty()) {
        		int tmp = q.front();
        		q.pop();
        		for(auto iter = edges.begin(); iter != edges.end(); iter++) {
           		if((*iter).first == tmp || (*iter).second == tmp) {
           			int newNode = (*iter).first + (*iter).second - tmp;
        	                if(!visited[newNode]) {
        	                        depth[newNode] = depth[tmp] + 1;
        	                        q.push(newNode);
        	                        visited[newNode] = 1;
        	                }
        	    	}
        	   }
            	}
        	int max = 0;
            	for(int i = 0; i < n; ++i) {
            		if(depth[i] > max)
            			max = depth[i];
            	}
            	return max;
            }
        };
        
      • 复杂度 – O ( V 2 E ) O(V^2E) O(V2E) (V表示节点数量,E表示边的数量)
      • 结果果然超时了
        在这里插入图片描述
      • 改进与优化
        • 可以利用map数据结构,来存储每个节点对应其连接的节点所组成的一个映射map<int, vector<int> >,或者一个二维数组
        • 复杂度 – O ( V E ) O(VE) O(VE) (V表示节点数量,E表示边的数量)
        • 优化的代码
          class Solution {
          public:
              vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
          	vector<int> v;
          	map<int, vector<int> > myMap;
          
                  int height[n];
          
                  for(auto iter = edges.begin(); iter != edges.end(); iter++) {
                      myMap[(*iter).first].push_back((*iter).second);
                      myMap[(*iter).second].push_back((*iter).first);
                  }
          
                  for(int i = 0; i < n; ++i) {
                      height[i] = getHeight(n, i, myMap);
                  }
          
                  // 寻找最小高度树的根节点
                  int min = n;
          	for(int i = 0; i < n; ++i) {
          		if(height[i] < min) {
                      		min = height[i];
          			v.clear();
          			v.push_back(i);
          		}
          		else if(height[i] == min) {
          			v.push_back(i);
          		}
          	}
          	return v;
          }
          
              // bfs遍历
              int getHeight(int n, int root, map<int, vector<int> > myMap) {
                  int h = 0;
                  int visited[n] = {0};
                  visited[root] = 1;
                  queue<int> q;
                  q.push(root);
                  int depth[n] = {0};
                  while(!q.empty()) {
                      int tmp = q.front();
                      q.pop();
                      for(auto iter = myMap[tmp].begin(); iter != myMap[tmp].end(); iter++) {
                          if(!visited[(*iter)]) {
                              depth[(*iter)] = depth[tmp] + 1;
                              q.push((*iter));
                              visited[(*iter)] = 1;
                          }
                      }
                  }
                  int max = 0;
                  for(int i = 0; i < n; ++i) {
                      if(depth[i] > max)
                          max = depth[i];
                  }
                  return max;
              }
          };
          
        • 但是依旧超时
          在这里插入图片描述
    • 思考提示:How many MHTs can a graph have at most?

      • 每个树最多有两个MHTs。假如有三个或多个可以作为MHTs的根节点,根据树的定义,每两个节点都可以找到一条路径连接起来,树是一个强连通的图,不存在简单环,则至少一个一个或多个比其余节点高,则大于三个MHTs不成立。
    • 解法2 – 类剥洋葱求解(AC)

      • 本方法学习自其他优秀解法
      • 步骤
        1. 建立一个映射表,记录每一个点与其直接相连的点
        2. 将树的叶节点(度为1的节点)加入一个队列中
        3. 假如当前队列中存储的节点数小于等于2,则退出循环。否则遍历队列中的每个节点。对每个节点,将其弹出队列,同时将与其相连节点的集合中将该节点删去,如果删完该节点后此节点也变成一个叶节点(度数为1),那么将这个节点加入队列中。
      • 时间复杂度 – O ( n ) O(n) O(n)
      • 实现代码
        class Solution {
        public:
            vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
                if(n == 1) return {0};
                vector<int> ans;
                vector<set<int> > myVec(n);
                for(auto edge : edges) {
                    myVec[edge.first].insert(edge.second);
                    myVec[edge.second].insert(edge.first);
                }
                queue<int> q;
                for(int i = 0; i < n; ++i)
                    if(myVec[i].size() == 1)
                        q.push(i);
        
                while(n > 2) {
                    int size = q.size();
                    n -= size;
                    for(int i = 0; i < size; ++i) {
                        int tmp = q.front();
                        q.pop();
                        for (auto it : myVec[tmp]) {
                            myVec[it].erase(tmp);
                            if (myVec[it].size() == 1) q.push(it);
                        }
                    }
                }
        
                while(!q.empty()) {
                    ans.push_back(q.front());
                    q.pop();
                }
        
                return ans;
            }
        };
        
Linux | Ubuntu18.04安装WIFI6 AX201驱动完整教程 本节介绍了如何在Ubuntu18下安装AX201驱动的教程。 阅读详情

相关推荐

DGX Spark上PyTorch GPU环境配置实战:CUDA 13.0与ARM架构全流程

在深度学习中,CUDA作为GPU加速计算的底层基础,其版本与深度学习框架(如PyTorch)的匹配直接影响模型训练的效率与稳定性。GPU环境配置不仅涉及驱动、CUDA工具链与框架运行时的协同,还依赖于硬件架构与预构建包的兼容性。在AI开发机Ubuntu系统上,正确对齐CUDA版本、计算能力架构及安装源,是避免环境故障、发挥硬件算力的关键。无论是面向个人AI超算还是通用GPU服务器,掌握版本对齐、路径隔离与验证方法,都能大幅提升开发效率。本文以DGX Spark为例,详解从环境摸底到PyTorch GPU版本

weixin_29483277的博客 228

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

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

zik的博客 765

全志T113 Tina5.0开发:(零)源码下载&修改调试串口

本文章主要作为自己的笔记,如有错误欢迎指出$ repo start product-da-t113-tina-stable --all # 全部下载完成之后,创建分支运行过程可能会出现版本问题;rm -rf .repo //先删除试试( 我安装的是3.6版本)

u014428915的博客 1175

leetcode 310. 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 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] = [

蓝羽飞鸟的博客 725

【UE5】Vosk插件实战:离线语音识别与TTS朗读全流程解析

本文详细解析了如何在UE5中利用Vosk插件实现离线实时语音转文字功能。从环境配置、插件与模型准备,到核心C++组件封装与蓝图系统搭建,提供了完整的实战教程。重点解决了离线语音识别在游戏开发中的延迟、隐私和网络依赖问题,并演示了从语音识别到TTS朗读的完整交互闭环,为开发安全、实时的语音交互应用提供可靠方案。

weixin_29021291的博客 529

手把手教你搞定国民技术N32G031的Keil开发环境(附Pack包和JLink配置)

本文详细指导如何搭建国民技术N32G031的Keil开发环境,包括Keil MDK安装与激活、Pack包导入、JLink调试器配置等关键步骤。特别针对新手常见问题提供解决方案,帮助开发者快速上手N32G031系列MCU的开发工作。

cuangu9341的博客 431

310. Minimum Height Trees

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

zdinanyang的博客 450

TYPE-C接口电路设计篇(一)

常见USB接口类型 随着USB Type-C接口的推行,USB Type-C是一种通用串行总线(USB)的硬件接口形式,USB Type-C接口在消费类产品普及程度越来越高,常见的适配器、笔电、手机等产品都兼容USB Type-C设计,接口多元化逐渐趋向归一,从而可以看出USB Type-C的重要性。 在了解USB Type-C接口之前,我们先来回顾下USB Type-A和USB Type-B接口,USB3.0 Type-A和Type-B接口定义分别如下。 USB 3.0...

JWu的博客 3万+

力扣 310. 最小高度树

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

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

虚拟机Ubuntu连接USRP

笔记本通过网线连接USRP。

xiaozir的博客 2325

LVGL 丝滑菜单3(Silk Menu)

h。

摸鱼专家 102

Leetcode: 310.Minimum Height Trees

Leetcode: 310.Minimum Height Trees

qq_16318319的博客 330

基于NSGA2算法的无人机三维路径规划MATLAB实现

传统的路径规划方法多采用启发式搜索算法,然而这些方法往往带着局限性,不能有效地克服无人机飞行任务中所遇到的复杂环境与约束。而基于遗传算法的NSGA2(Non-dominated Sorting Genetic Algorithm II)方法则可以在优化目标之间找到最好的平衡点,是一种十分优秀的解决方案。本文介绍了基于NSGA2算法的无人机三维路径规划MATLAB实现。NSGA2算法是一种多目标优化算法,通过非支配排序和拥挤度距离来评估个体的适应度和选择新个体,从而产生一组非支配解。3.选择新个体组成P1;

CyberLynxX的博客 986

leetcode 310 : Minimum Height Trees

1、原题如下: 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 ca

l3368bcttqnqn的博客 540

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

LeetCode: 310. Minimum Height Trees

LeetCode: 310. Minimum Height Trees 题目描述 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 rooted trees,...

杨领well的专栏 251

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

草稿:Leetcode 310. Minimum Height Trees

这个思路是先构建一个树,然后不断地移动根节点的子节点到根节点的位置,但这个过程中需要实现的部分感觉很多,写了一半写不下去了,下面是未完成的草稿 import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java

独钓寒江雪 346

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

LeetCode Graph:M310. 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

iyangdi的博客 329

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_30753873的博客 129

Ruby超时算法:Leetcode 310. 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 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] = [

Fourier_xyz的博客 195

[算法分析与设计] leetcode 每周一题: 310. Minimum Height Trees

题目链接:  310. Minimum Height Trees 题目大意: 给定一个具有树的性质的无向图, 选择其中任意一个节点作为根节点即可生成一棵有根树, 所有不同的生成树中, 高度最小的那些便被称为 minimum height trees (MHTs), 现要求找出 给定无向图的 MHTs, 返回结果为 各MHT 的根节点(对应的 label) ;

sinat_37893507的博客 404

leetcode_c++:图:Minimum Height Trees(310)

class Solution { public: vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) { //corner case if ( n <= 1 ) return {0}; //construct a edges search data stuctu

LandscapeMi 579

[LeetCode] 310. Minimum Height Trees_Medium tag: BFS

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 mi...

weixin_30271335的博客 123

Leetcode 310. Minimum Height Trees

310. Minimum Height Trees 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 rooted trees, those with min...

大洋深处 279

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:64. Minimum Path Sum
下一篇: LeetCode:332. Reconstruct Itinerary
zerokk9912
博客等级 码龄10年 171粉丝 74原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值