Skip to content

Commit 0902dce

Browse files
add post '(Leetcode) 261 - Graph Valid Tree'
1 parent 25aeb74 commit 0902dce

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

_posts/2024-07-02-leetcode-261.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
---
2+
layout: post
3+
title: (Leetcode) 261 - Graph Valid Tree
4+
categories: [스터디-알고리즘]
5+
tags:
6+
[자바, java, 리트코드, Leetcode, 알고리즘, tree, node, vertex, edge, degree]
7+
date: 2024-07-02 19:30:00 +0900
8+
toc: true
9+
---
10+
11+
기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다.
12+
13+
[https://neetcode.io/practice](https://neetcode.io/practice)
14+
15+
---
16+
17+
유료 : [https://leetcode.com/problems/graph-valid-tree/](https://leetcode.com/problems/graph-valid-tree/)
18+
무료 : [https://neetcode.io/problems/valid-tree](https://neetcode.io/problems/valid-tree)
19+
20+
## 내가 작성한 풀이
21+
22+
```java
23+
public class Solution {
24+
public boolean validTree(int n, int[][] edges) {
25+
int[] degrees = new int[n];
26+
27+
for (int[] edge : edges) {
28+
int largeOne = Math.max(edge[0], edge[1]);
29+
if (degrees[largeOne] == 0) {
30+
degrees[largeOne] += 1;
31+
} else {
32+
return false;
33+
}
34+
}
35+
36+
int zeroCount = 0;
37+
for (int degree : degrees) {
38+
if (degree == 0) {
39+
zeroCount++;
40+
}
41+
42+
if (zeroCount > 1) {
43+
return false;
44+
}
45+
}
46+
47+
return zeroCount == 1;
48+
}
49+
}
50+
```
51+
52+
다음과 같이 가정을 하고 풀었다.
53+
54+
- 루트를 제외한 모든 노드는 1개의 부모를 가진다.
55+
- 루트는 부모를 가지지 않는다.
56+
57+
따라서 각 노드로 들어오는 수를 세어봤을 때 루트에는 들어오는 간선이 없어야 하며, 나머지 노드는 1개의 간선이 있어야 한다.
58+
59+
### TC, SC
60+
61+
시간 복잡도는 O(n)이다. 공간 복잡도는 O(n)이다. 시간 복잡도를 조금 더 디테일 하게 보자면 간선 의 수도 포함을 시킬 수 있을 것이다.

0 commit comments

Comments
 (0)