题目
给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
解
class Solution {public List<List<Integer>> levelOrder(TreeNode root) {List<List<Integer>> result = new ArrayList<>();if (root == null) {return result;}LinkedList<TreeNode> queue = new LinkedList<>();LinkedList<TreeNode> queue2 = new LinkedList<>();queue.offer(root);List<Integer> res = new ArrayList<>();while (!queue.isEmpty()) {TreeNode poll = queue.poll();res.add(poll.val);if (poll.left != null) {queue2.offer(poll.left);}if (poll.right != null) {queue2.offer(poll.right);}if (queue.isEmpty()) {result.add(res);res = new ArrayList<>();queue = queue2;queue2 = new LinkedList<>();}}return result;}
}