题目描述:二叉树的层序遍历,按层数输出每一层的结果数组
代码实现
class Solution {public List<List<Integer>> levelOrder(TreeNode root) {List<List<Integer>> res = new ArrayList<List<Integer>>();Queue<TreeNode> queue = new ArrayDeque<>();if(root != null){queue.add(root);}while(!queue.isEmpty()){int n = queue.size();List<Integer> level = new ArrayList<>();for (int i = 0; i < n; i++) { TreeNode node = queue.poll();level.add(node.val);if (node.left != null) {queue.add(node.left);}if (node.right != null) {queue.add(node.right);}}res.add(level);}return res;}
}