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,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
Subscribe to see which companies asked this question
public class Solution {
private Queue<TreeNode> q = new LinkedList<TreeNode>();
List<List<Integer>> lists = new ArrayList<List<Integer>>();
public List<List<Integer>> levelOrder(TreeNode root) {
if(root!= null){
core(root);
}
return lists;
}
private void core(TreeNode root){
q.offer(root);
int count = 1;
int nextCount = 0;
while(!q.isEmpty()){
List<Integer> list = new ArrayList<Integer>();
for(int i= 0 ;i<count;i++){
TreeNode node = q.poll();
list.add(node.val);
if(node.left!=null){
q.offer(node.left);
nextCount++;
}
if(node.right!=null){
q.offer(node.right);
nextCount++;
}
}
lists.add(list);
count = nextCount;
nextCount = 0;
}
}
}