Skip to content

[mangodm-web] Week11 Solutions #556

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions graph-valid-tree/mangodm-web.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from typing import List


class Solution:
def validTree(self, n: int, edges: List[List[int]]) -> bool:
"""
- Idea: 유효한 트리라면 만족해야 하는 조건들을 활용하여 트리 여부를 판단한다.
- Time Complexity: O(v + e). v와 e는 각각 노드의 수, 연결된 선(엣지)의 수
인접 리스트로 만든 그래프를 순회할 때, 노드마다 연결된 엣지를 따라가며 탐색하므로 O(v + e)이 소요된다.
- Space Complexity: O(v + e). v와 e는 각각 노드의 수, 엣지의 수
그래프를 인접 리스트로 저장하기 위해 O(v + e)의 공간이 필요하다.

"""
if len(edges) != n - 1:
return False

graph = {i: [] for i in range(n)}

for v1, v2 in edges:
graph[v1].append(v2)
graph[v2].append(v1)

visited = set()

def DFS(v: int) -> None:
visited.add(v)

for adj in graph[v]:
if adj not in visited:
DFS(adj)

DFS(0)

return len(visited) == n
28 changes: 28 additions & 0 deletions maximum-depth-of-binary-tree/mangodm-web.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from typing import Optional


# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right


class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""
- Idea: 이진 트리의 최대 깊이는 현재 노드의 깊이(1)와 하위 트리의 최대 깊이 중 큰 값을 더한 것으로 정의한다.
- Time Complexity: O(n). n은 전체 노드의 수
모든 노드를 한번씩 방문하여 탐색하기 때문에 O(n)이 소요된다.
- Space Complexity: O(n). n은 전체 노드의 수
재귀적으로 탐색할 때, 호출 스택에 쌓이는 함수 호출의 수는 최대 트리의 깊이와 같다.
트리가 편향되어 있는 최악의 경우, 깊이가 n이 될 수 있기 때문에 O(n)으로 표현할 수 있다.
"""
if root is None:
return 0

left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)

return max(left_depth, right_depth) + 1
45 changes: 45 additions & 0 deletions reorder-list/mangodm-web.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from typing import Optional


# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next


class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
"""
- Idea:
연결 리스트를 반으로 나누고, 뒤쪽(두번째 리스트)의 연결 방향을 반대로 뒤집는다.
첫번째 리스트와 두번째 리스트의 노드를 번갈아가며 연결한다.
- Time Complexity: O(n). n은 전체 노드의 수
리스트를 탐색하고 병합하는 데 걸리는 시간에 비례한다.
- Space Complexity: O(1)
몇 개의 포인터를 사용하는 상수 공간만 차지한다.
"""
slow, fast = head, head

while fast and fast.next:
slow = slow.next
fast = fast.next.next

mid = slow.next
slow.next = None

prev, cur = None, mid

while cur:
next_temp = cur.next
cur.next = prev
prev = cur
cur = next_temp

first, second = head, prev

while second:
first_next, second_next = first.next, second.next
first.next = second
second.next = first_next
first, second = first_next, second_next