给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

    示例 1:
    image.png

    输入:root = [3,9,20,null,null,15,7]
    输出:[[3],[9,20],[15,7]]
    示例 2:

    输入:root = [1]
    输出:[[1]]
    示例 3:

    输入:root = []
    输出:[]

    提示:

    树中节点数目在范围 [0, 2000] 内
    -1000 <= Node.val <= 1000


    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode() {}
    8. * TreeNode(int val) { this.val = val; }
    9. * TreeNode(int val, TreeNode left, TreeNode right) {
    10. * this.val = val;
    11. * this.left = left;
    12. * this.right = right;
    13. * }
    14. * }
    15. */
    16. class Solution {
    17. public List<List<Integer>> levelOrder(TreeNode root) {
    18. List<List<Integer>> res = new ArrayList<>();
    19. if (root == null) return res;
    20. Deque<TreeNode> queue = new LinkedList<>();
    21. queue.addLast(root);
    22. while (!queue.isEmpty()) {
    23. int size = queue.size();
    24. List<Integer> list = new ArrayList<>();
    25. while (size -- > 0) {
    26. TreeNode t = queue.pollFirst();
    27. list.add(t.val);
    28. if (t.left != null) queue.addLast(t.left);
    29. if (t.right != null) queue.addLast(t.right);
    30. }
    31. res.add(new ArrayList(list));
    32. }
    33. return res;
    34. }
    35. }