Skip to content

Commit 7ddce94

Browse files
authored
[sonshn] WEEK 04 Solutions (#2754)
* merge two sorted lists solution * maximum depth of binary tree solution
1 parent 1d03474 commit 7ddce94

2 files changed

Lines changed: 77 additions & 0 deletions

File tree

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* ์ด์ง„ ํŠธ๋ฆฌ์˜ ์ตœ๋Œ€ ๊นŠ์ด๋ฅผ ์žฌ๊ท€์ ์œผ๋กœ ๊ณ„์‚ฐ (DFS)
3+
*
4+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n), n์€ ํŠธ๋ฆฌ์˜ ๋…ธ๋“œ ์ˆ˜
5+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(h), h๋Š” ํŠธ๋ฆฌ์˜ ๋†’์ด, ์žฌ๊ท€ ํ˜ธ์ถœ๋กœ ์ธํ•ด ์Šคํƒ์— ์Œ“์ด๋Š” ํ•จ์ˆ˜ ํ˜ธ์ถœ์˜ ๊นŠ์ด ๋•Œ๋ฌธ
6+
*/
7+
class Solution {
8+
public int maxDepth(TreeNode root) {
9+
if (root == null) {
10+
return 0;
11+
}
12+
13+
int leftDepth = maxDepth(root.left);
14+
int rightDepth = maxDepth(root.right);
15+
16+
return Math.max(leftDepth, rightDepth) + 1;
17+
}
18+
}
19+
20+
/**
21+
* ์ด์ง„ ํŠธ๋ฆฌ์˜ ์ตœ๋Œ€ ๊นŠ์ด๋ฅผ ๋ฐ˜๋ณต์ ์œผ๋กœ ๊ณ„์‚ฐ (BFS)
22+
*
23+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n), n์€ ํŠธ๋ฆฌ์˜ ๋…ธ๋“œ ์ˆ˜
24+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(n), ํ์— ์ €์žฅ๋˜๋Š” ๋…ธ๋“œ ์ˆ˜ ๋•Œ๋ฌธ
25+
*/
26+
class Solution {
27+
public int maxDepth(TreeNode root) {
28+
if (root == null) {
29+
return 0;
30+
}
31+
32+
Queue<TreeNode> queue = new LinkedList<>();
33+
queue.offer(root);
34+
35+
int depth = 0;
36+
37+
while (!queue.isEmpty()) {
38+
int size = queue.size();
39+
40+
for (int i = 0; i < size; i++) {
41+
TreeNode current = queue.poll();
42+
43+
if (current.left != null) {
44+
queue.offer(current.left);
45+
}
46+
47+
if (current.right != null) {
48+
queue.offer(current.right);
49+
}
50+
}
51+
52+
depth++;
53+
}
54+
55+
return depth;
56+
}
57+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* ์žฌ๊ท€๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋‘ ๊ฐœ์˜ ์ •๋ ฌ๋œ ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ณ‘ํ•ฉ
3+
*
4+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n + m), n์€ list1์˜ ๊ธธ์ด, m์€ list2์˜ ๊ธธ์ด
5+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(n + m), ์žฌ๊ท€ ํ˜ธ์ถœ๋กœ ์ธํ•ด ์Šคํƒ์— ์Œ“์ด๋Š” ํ•จ์ˆ˜ ํ˜ธ์ถœ์˜ ๊นŠ์ด ๋•Œ๋ฌธ
6+
*/
7+
class Solution {
8+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
9+
if (list1 == null) return list2;
10+
if (list2 == null) return list1;
11+
12+
if (list1.val <= list2.val) {
13+
list1.next = mergeTwoLists(list1.next, list2);
14+
return list1;
15+
} else {
16+
list2.next = mergeTwoLists(list1, list2.next);
17+
return list2;
18+
}
19+
}
20+
}

0 commit comments

Comments
ย (0)