Question
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
Code
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> results = new ArrayList<>();
if (root == null) {
return results;
}
Queue<TreeNode> queues = new ArrayDeque<>();
queues.add(root);
while (!queues.isEmpty()) {
int len = queues.size();
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < len; i++) {
TreeNode remove = queues.remove();
temp.add(remove.val);
if (remove.left != null) {
queues.add(remove.left);
}
if (remove.right != null) {
queues.add(remove.right);
}
}
results.add(temp);
}
return results;
}