forked from soulmachine/algorithm-essentials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-level-order-traversal-2.java
More file actions
31 lines (29 loc) · 1021 Bytes
/
binary-tree-level-order-traversal-2.java
File metadata and controls
31 lines (29 loc) · 1021 Bytes
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
// Binary Tree Level Order Traversal
// 迭代版,时间复杂度O(n),空间复杂度O(1)
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
Queue<TreeNode> current = new LinkedList<>();
Queue<TreeNode> next = new LinkedList<>();
if(root == null) {
return result;
} else {
current.offer(root);
}
while (!current.isEmpty()) {
ArrayList<Integer> level = new ArrayList<>(); // elments in one level
while (!current.isEmpty()) {
TreeNode node = current.poll();
level.add(node.val);
if (node.left != null) next.add(node.left);
if (node.right != null) next.add(node.right);
}
result.add(level);
// swap
Queue<TreeNode> tmp = current;
current = next;
next = tmp;
}
return result;
}
}