-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBinaryTreeLevelOrderTraversal.java
More file actions
41 lines (41 loc) · 1.22 KB
/
BinaryTreeLevelOrderTraversal.java
File metadata and controls
41 lines (41 loc) · 1.22 KB
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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
List<List<Integer>> allLevels = new ArrayList<>();
List<Integer> thisLevel = new ArrayList<>();
int thisLevelCount = 1, nextLevelCount = 0;
while (!q.isEmpty()) {
TreeNode node = q.poll();
thisLevel.add(node.val);
--thisLevelCount;
if (node.left != null) {
q.offer(node.left);
++nextLevelCount;
}
if (node.right != null) {
q.offer(node.right);
++nextLevelCount;
}
if (thisLevelCount == 0) {
thisLevelCount = nextLevelCount;
nextLevelCount = 0;
allLevels.add(thisLevel);
thisLevel = new ArrayList<>();
}
}
return allLevels;
}
}