Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.

Example 1:

Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
Output: true

Example 2:

Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
Output: false

Note: 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.

这个题的思路就是BFS, 另外注意有效的tree的条件是nodes number == number of edges + 1 and connects all nodes, 所以首先用这个条件去掉所有点连通并且有loop的情况, 所以还有两种情况, 一种是valid tree, 另一种是有重复的loop, 但是不连通, 所以我们用BFS选择任一点开始, 我们选择0, 因为所有情况都包括0这个node, 然后BFS, 最后把visited set的size跟input n比较是否相等, 如果相等, valid, 否则不valid.

1. Constraints

1) n <=0 时, False

2) n =1是, edge = []  =>  True

3) no duplicates and (1,0) and (0,1) will not exist at same time, 这个条件保证了nodes number == number of edges + 1 的判断依据

2. Ideas

BFS     T: O(n)     S: O(n)

1) edge case, n <=0 时, False

2) transform input into a dictionary

3) start from 0 , BFS, save all visited nodes into a visited set

4) return len(visited) == n

3. Code

 class Solution:
def validTree(self, n, edges):
if n <= 0: return False
d, queue, visited = collections.defaultdict(set), collections.deque([0]), set([0])
for n1, n2 in edges:
d[n1].add(n2)
d[n2].add(n1)
while queue:
node = queue.popleft()
for each in d[node]:
if each not in visited:
queue.append(node)
visited.add(node)
return len(visited) == n

4. Test cases

1)  1, []  => True

2) 3, [[0,1], [0,2]]    => True

3) 5, [[0,1], [3, 4], [3,5], [4,5]]  =>   False

[LeetCode] 261. Graph Valid Tree _ Medium tag: BFS的更多相关文章

  1. [LeetCode] 261. Graph Valid Tree 图是否是树

    Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), ...

  2. [LeetCode#261] Graph Valid Tree

    Problem: Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair o ...

  3. [LeetCode] 513. Find Bottom Left Tree Value_ Medium tag: BFS

    Given a binary tree, find the leftmost value in the last row of the tree. Example 1: Input: 2 / \ 1 ...

  4. [LeetCode] 103. Binary Tree Zigzag Level Order Traversal _ Medium tag: BFS

    Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to ...

  5. 261. Graph Valid Tree

    题目: Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nod ...

  6. [Locked] Graph Valid Tree

    Graph Valid Tree Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is ...

  7. [LeetCode] Graph Valid Tree 图验证树

    Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), ...

  8. LeetCode Graph Valid Tree

    原题链接在这里:https://leetcode.com/problems/graph-valid-tree/ 题目: Given n nodes labeled from 0 to n - 1 an ...

  9. Leetcode: Graph Valid Tree && Summary: Detect cycle in undirected graph

    Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), ...

随机推荐

  1. 关于android性能,内存优化

    转:http://www.starming.com/index.php?action=plugin&v=wave&tpl=union&ac=viewgrouppost& ...

  2. Kafka+Storm+HDFS 整合示例

    消息通过各种方式进入到Kafka消息中间件,比如可以通过使用Flume来收集日志数据,然后在Kafka中路由暂存,然后再由实时计算程序Storm做实时分析,最后将结果保存在HDFS中,这时我们就需要将 ...

  3. LeetCode 78 Subsets (所有子集)

    题目链接:https://leetcode.com/problems/subsets/#/description   给出一个数组,数组中的元素各不相同,找到该集合的所有子集(包括空集和本身) 举例说 ...

  4. Unix/Linux 查看文件大小

    ls -l help.html-rw-r--r--  1 william  wheel  40960 Jul 18 00:59 development.sqlite3 40960 就是文件的大小. d ...

  5. 遮挡剔除 Occlusion Culling(转)

    一.首先介绍下draw call(这个东西越少你的游戏跑的越快): 在游戏中每一个被展示的独立的部分都被放在了一个特别的包中,我们称之为“描绘指令”(draw call),然后这个包传递到3D部分在屏 ...

  6. nodejs事件的监听与事件的触发

    nodejs事件(Events) 一.事件机制的实现 Node.js中大部分的模块,都继承自Event模块(http://nodejs.org/docs/latest/api/events.html  ...

  7. Ubuntu 16.04系统下解决Vim乱码问题

    方法: 打开终端输入:vim /etc/vim/vimrc,进入编辑模式,加入如下配置: set fileencodings=utf-8,gb2312,gbk,gb18030 set termenco ...

  8. 基础回顾—list遍历4种

    ()for each for(bject o :list) { } [java] view plain copy ()Iterator Iterator iter = list.iterator(); ...

  9. Bazel构建工具的安装

    官方Doc:https://docs.bazel.build/versions/master/install-ubuntu.html 使用Bazel定制的APT存储库 (recommended) 1. ...

  10. iOS电话等中断事件的开始和结束通知

    #import "ViewController.h" #import <AVFoundation/AVFoundation.h> @interface ViewCont ...