力扣-102. 二叉树的层序遍历
题目链接
102. 二叉树的层序遍历
class Solution {public List<List<Integer>> levelOrder(TreeNode root) {List<List<Integer>> res = new ArrayList<>();Queue<TreeNode> queue = new LinkedList<>(); //注意写法if (root == null)return res;queue.offer(root);while (!queue.isEmpty()) {int size = queue.size();List<Integer> path = new ArrayList<>();for (int i = 0; i < size; i++) { // 这里不能直接用queue.size(),因为在循环里面会变TreeNode temp = queue.poll();path.add(temp.val);if (temp.left != null)queue.add(temp.left);if (temp.right != null)queue.add(temp.right);}res.add(path);}return res;}
}
小结:思路比较简单,用队列每层结点轮流出队,左孩子右孩子依次进队,需要注意一些小细节在上面注释中。