问题
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例子
思路
- 队列存储结点
- 获取每层的个数width,然后从队列中拉出来width个结点
代码
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
if(root==null) return list;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while(!q.isEmpty()) {
int width = q.size();//该层的结点个数
List<Integer> list2 = new ArrayList<>();
for(int i=0; i<width; i++){
TreeNode node = q.poll();
list2.add(node.val);
if(node.left!=null) q.offer(node.left);
if(node.right!=null) q.offer(node.right);
}
list.add(list2);
}
return list;
}
}