Skip to content

Commit 850f628

Browse files
committed
add binary tree level order traversal solution
1 parent 02b7a35 commit 850f628

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import java.util.ArrayList;
2+
import java.util.LinkedList;
3+
import java.util.List;
4+
import java.util.Queue;
5+
6+
/**
7+
* Definition for a binary tree node.
8+
* public class TreeNode {
9+
* int val;
10+
* TreeNode left;
11+
* TreeNode right;
12+
* TreeNode() {}
13+
* TreeNode(int val) { this.val = val; }
14+
* TreeNode(int val, TreeNode left, TreeNode right) {
15+
* this.val = val;
16+
* this.left = left;
17+
* this.right = right;
18+
* }
19+
* }
20+
*/
21+
class Solution {
22+
23+
// DFS 풀이
24+
public List<List<Integer>> levelOrder(TreeNode root) {
25+
List<List<Integer>> result = new ArrayList<>();
26+
dfs(root, 0, result);
27+
return result;
28+
}
29+
30+
private void dfs(TreeNode node, int depth, List<List<Integer>> result) {
31+
if (node == null) {
32+
return;
33+
}
34+
35+
// 깊이만큼의 리스트가 없으면 새 리스트 추가하기
36+
if (depth == result.size()) {
37+
result.add(new ArrayList<>());
38+
}
39+
40+
result.get(depth).add(node.val);
41+
42+
dfs(node.left, depth + 1, result);
43+
dfs(node.right, depth + 1, result);
44+
45+
46+
}
47+
48+
// BFS로 풀이
49+
// O(n)
50+
// public List<List<Integer>> levelOrder(TreeNode root) {
51+
//
52+
// List<List<Integer>> result = new ArrayList<>();
53+
//
54+
// if (root == null) {
55+
// return result;
56+
// }
57+
//
58+
// Queue<TreeNode> queue = new LinkedList<>();
59+
// queue.offer(root);
60+
//
61+
// while (!queue.isEmpty()) {
62+
// int nodeCnt = queue.size();
63+
// List<Integer> currentLevelNodes = new ArrayList<>();
64+
//
65+
// for (int i = 0; i < nodeCnt; i++) {
66+
// TreeNode current = queue.poll();
67+
// currentLevelNodes.add(current.val);
68+
//
69+
// if (current.left != null) {
70+
// queue.offer(current.left);
71+
// }
72+
//
73+
// if (current.right != null) {
74+
// queue.offer(current.right);
75+
// }
76+
//
77+
// }
78+
//
79+
// result.add(currentLevelNodes);
80+
//
81+
// }
82+
//
83+
// return result;
84+
//
85+
// }
86+
}
87+

0 commit comments

Comments
 (0)