class TreeNode{
int val;
TreeNode left,right;
TreeNode(int val){
this.val=val;
}
}
public class LevelOrderOfBinaryTree {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
System.out.println(solution(root));
}
private static List<List<Integer>> solution(TreeNode tree) {
List<List<Integer>> result = new ArrayList<>();
if(tree==null) return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(tree);
while(!queue.isEmpty()){
List<Integer> list = new LinkedList<>();
int size = queue.size();
for(int i=0;i< size;i++){
TreeNode pollNode = queue.poll();
list.add(pollNode.val);
if(pollNode.left!=null){
queue.offer(pollNode.left);
}
if(pollNode.right!=null){
queue.offer(pollNode.right);
}
}
result.add(list);
}
return result;
}
}