forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution2.java
51 lines (41 loc) · 1.32 KB
/
Solution2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/// Source : https://leetcode.com/problems/binary-tree-level-order-traversal/description/
/// Author : liuyubobobo
/// Time : 2018-10-16
import java.util.ArrayList;
import java.util.List;
import java.util.LinkedList;
import java.util.Queue;
/// BFS
/// No need to store level information in the queue :-)
///
/// Time Complexity: O(n), where n is the number of nodes in the tree
/// Space Complexity: O(n)
class Solution2 {
public List<List<Integer>> levelOrder(TreeNode root) {
ArrayList<List<Integer>> res = new ArrayList<>();
if(root == null)
return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int levelNum = 1;
while(!queue.isEmpty()){
int newLevelNum = 0;
ArrayList<Integer> level = new ArrayList<>();
for(int i = 0; i < levelNum; i ++){
TreeNode node = queue.remove();
level.add(node.val);
if(node.left != null){
queue.add(node.left);
newLevelNum ++;
}
if(node.right != null){
queue.add(node.right);
newLevelNum ++;
}
}
res.add(level);
levelNum = newLevelNum;
}
return res;
}
}