Skip to content

Commit f281574

Browse files
add post '(Leetcode) 102 - Binary Tree Level Order Traversal'
1 parent b1442ad commit f281574

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

_posts/2024-06-10-leetcode-102.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
---
2+
layout: post
3+
title: (Leetcode) 102 - Binary Tree Level Order Traversal
4+
categories: [스터디-알고리즘]
5+
tags: [자바, java, 리트코드, Leetcode, 알고리즘, algorithm, tree, dfs, node]
6+
date: 2024-06-10 01:00:00 +0900
7+
toc: true
8+
---
9+
10+
기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다.
11+
12+
[https://neetcode.io/practice](https://neetcode.io/practice)
13+
14+
---
15+
16+
[https://leetcode.com/problems/binary-tree-level-order-traversal/](https://leetcode.com/problems/binary-tree-level-order-traversal/)
17+
18+
## 내가 작성한 풀이
19+
20+
```java
21+
class Solution {
22+
public List<List<Integer>> levelOrder(TreeNode root) {
23+
List<List<Integer>> result = new ArrayList<>();
24+
25+
dfs(result, root, 0);
26+
27+
return result;
28+
}
29+
30+
public void dfs(List<List<Integer>> result, TreeNode node, int level) {
31+
if(node == null) {
32+
return;
33+
}
34+
35+
if (result.size() <= level) {
36+
result.add(new ArrayList<>());
37+
}
38+
result.get(level).add(node.val);
39+
40+
dfs(result, node.left, level + 1);
41+
dfs(result, node.right, level + 1);
42+
}
43+
}
44+
```
45+
46+
### TC, SC
47+
48+
시간 복잡도는 O(n)이고, 공간 복잡도는 O(n)이다. 트리가 균등한 형태일 경우 공간 복잡도는 O(logn)에 가까워진다. (결과에 사용되는 list는 고려하지 않는다.)

0 commit comments

Comments
 (0)