Skip to content

Commit 291986b

Browse files
authored
Merge pull request #1359 from river20s/main
[river20s] WEEK 04 solutions
2 parents 855df9d + 11bcf09 commit 291986b

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import collections
2+
3+
# Definition for a binary tree node.
4+
class TreeNode(object):
5+
def __init__(self, val=0, left=None, right=None):
6+
self.val = val
7+
self.left = left
8+
self.right = right
9+
10+
class Solution(object):
11+
def maxDepth(self, root):
12+
"""
13+
:type root: Optional[TreeNode]
14+
:rtype: int
15+
์ฃผ์–ด์ง„ ์ด์ง„ ํŠธ๋ฆฌ์˜ ์ตœ๋Œ€ ๊นŠ์ด(๋ฃจํ”„์—์„œ ๋ฆฌํ”„๊นŒ์ง€์˜ ๊ฐ€์žฅ ๊ธด ๊ฒฝ๋กœ์˜ ๋…ธ๋“œ ์ˆ˜)๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ
16+
BFS๋กœ ํ๋ฅผ ์‚ฌ์šฉํ•ด ์ตœ๋Œ€ ๊นŠ์ด๋ฅผ ๊ตฌํ•จ.
17+
Time complexity: O(n), n๊ฐœ์˜ ๋…ธ๋“œ๋ฅผ ํ•œ ๋ฒˆ์”ฉ ๋ฐฉ๋ฌธ.
18+
Space complexity: O(w), w๋Š” ํŠธ๋ฆฌ์˜ ์ตœ๋Œ€ ๋„ˆ๋น„ (n/2).
19+
"""
20+
if root is None:
21+
return 0
22+
23+
depth = 0
24+
25+
queue = collections.deque([root])
26+
27+
while queue:
28+
depth += 1
29+
level_size = len(queue)
30+
for _ in range(level_size):
31+
node = queue.popleft()
32+
if node.left is not None:
33+
queue.append(node.left)
34+
if node.right is not None:
35+
queue.append(node.right)
36+
return depth
+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Definition for singly-linked list.
2+
class ListNode(object):
3+
def __init__(self, val=0, next=None):
4+
self.val = val
5+
self.next = next
6+
7+
class Solution(object):
8+
def mergeTwoLists(self, list1, list2):
9+
"""
10+
:type list1: Optional[ListNode]
11+
:type list2: Optional[ListNode]
12+
:rtype: Optional[ListNode]
13+
- TC: O(m+n)
14+
- SC: O(1)
15+
"""
16+
17+
# ์—ฃ์ง€ ์ผ€์ด์Šค
18+
# ๋‘ ๋ฆฌ์ŠคํŠธ ์ค‘ ํ•˜๋‚˜๋ผ๋„ ๋น„์–ด ์žˆ๋Š” ๊ฒฝ์šฐ,
19+
# ๋‚˜๋จธ์ง€ ๋ฆฌ์ŠคํŠธ ๋ฐ”๋กœ ๋ฐ˜ํ™˜
20+
if not list1:
21+
return list2
22+
if not list2:
23+
return list1
24+
25+
# ๋”๋ฏธ ํ—ค๋“œ ๋…ธ๋“œ
26+
# ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ ์‹œ์ž‘์  ์—ญํ• ์„ ํ•  ๊ฐ€์งœ ๋…ธ๋“œ ์ƒ์„ฑ
27+
dummy = ListNode()
28+
current = dummy # current๋Š” ํ˜„์žฌ๊นŒ์ง€ ๋งŒ๋“  ๋ฆฌ์ŠคํŠธ์˜ ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ
29+
30+
# ๋‘ ๋ฆฌ์ŠคํŠธ ๋ชจ๋‘ ๋…ธ๋“œ๊ฐ€ ๋‚จ์•„ ์žˆ์„ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต
31+
while list1 and list2:
32+
if list1.val <= list2.val:
33+
current.next = list1
34+
list1 = list1.next
35+
else:
36+
current.next = list2
37+
list2 = list2.next
38+
current = current.next
39+
40+
# ๋‚จ์€ ๋…ธ๋“œ๋“ค ์ด์–ด ๋ถ™์ด๊ธฐ
41+
# ์•„์ง ๋…ธ๋“œ๊ฐ€ ๋‚จ์•„ ์žˆ๋Š” ๋ฆฌ์ŠคํŠธ๊ฐ€ ์žˆ์œผ๋ฉด ํ†ต์งธ๋กœ ๋ถ™์ด๊ธฐ
42+
if list1:
43+
current.next = list1
44+
elif list2:
45+
current.next = list2
46+
47+
return dummy.next

0 commit comments

Comments
ย (0)