[NeetCode 150] Valid Tree

16 篇文章 0 订阅

Valid Tree

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
edges = [[0, 1], [0, 2], [0, 3], [1, 4]]

Output:
true

Example 2:

Input:
n = 5
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.
Constraints:

1 <= n <= 100
0 <= edges.length <= n * (n - 1) / 2

Solution

To check if this graph is a tree, there are 2 principles.

  1. There cannot be a loop.
  2. All the nodes are connected.

DFS can easily check the principles above. All we need to do is to record whether we have visited a node. If we reach a node that has been visited before and the node is not parent node the current node, there is a loop.

After one DFS, if there are still nodes that has not been visited, not all nodes are connected.

Code

class Solution:
    def validTree(self, n: int, edges: List[List[int]]) -> bool:
        vis_flag = [False] * n
        tree_map = {i: [] for i in range(n)}
        for edge in edges:
            tree_map[edge[0]].append(edge[1])
            tree_map[edge[1]].append(edge[0])
        def dfs(father, curr):
            vis_flag[curr] = True
            for nxt in tree_map[curr]:
                if nxt == father:
                    continue
                if vis_flag[nxt]:
                    return False
                if not dfs(curr, nxt):
                    return False
            return True
        if not dfs(None, 0):
            return False
        for flag in vis_flag:
            if not flag:
                return False
        return True
        

        
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ShadyPi

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

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

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

打赏作者

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

抵扣说明:

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

余额充值