102. Binary Tree Level Order Traversal
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] ]
题目含义:按照从左到右的顺序,输出每一层的节点
1 public List<List<Integer>> levelOrder(TreeNode root) { 2 List<List<Integer>> result = new ArrayList<>(); 3 if (root == null) return result; 4 Queue<TreeNode> q = new LinkedList<>(); 5 q.add(root); 6 while (!q.isEmpty()) 7 { 8 int size = q.size(); 9 List<Integer> levels = new ArrayList<>(); 10 for (int i=0;i<size;i++) 11 { 12 TreeNode node = q.poll(); 13 levels.add(node.val); 14 if (node.left !=null) q.offer(node.left); 15 if (node.right !=null) q.offer(node.right); 16 } 17 result.add(levels); 18 } 19 return result; 20 }