给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> layers = new ArrayList<List<Integer>>();
if (root == null) {
return layers;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
Queue<TreeNode> newQueue = new LinkedList<TreeNode>();
List<Integer> layer = new ArrayList<>();
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
layer.add(node.val);
if (node.left != null) {
newQueue.offer(node.left);
}
if (node.right != null) {
newQueue.offer(node.right);
}
};
layers.add(layer);
queue = newQueue;
};
return layers;
}
}