-
Notifications
You must be signed in to change notification settings - Fork 0
/
LevelOrder.java
42 lines (42 loc) · 1.3 KB
/
LevelOrder.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
/**
* Problem: https://leetcode.com/problems/binary-tree-level-order-traversal/description/
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> order = new ArrayList<List<Integer>>();
if (root == null) return order;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
List<Integer> res = new ArrayList<Integer>();
int parentQueueSize=0, childQueueSize=0;a
queue.add(root);
parentQueueSize++;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
parentQueueSize--;
res.add(node.val);
if (node.left != null) {
queue.add(node.left);
childQueueSize++;
}
if (node.right != null) {
queue.add(node.right);
childQueueSize++;
}
if (parentQueueSize == 0) {
parentQueueSize = childQueueSize;
childQueueSize = 0;
order.add(res);
res = new ArrayList<Integer>();
}
}
return order;
}
}