Given the root of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).

    Example 1:
    102. Binary Tree Level Order Traversal - 图1

    Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]]
    Example 2:
    Input: root = [1] Output: [[1]]
    Example 3:
    Input: root = [] Output: []

    Constraints:

    • The number of nodes in the tree is in the range [0, 2000].
    • -1000 <= Node.val <= 1000

    Runtime: 80 ms, faster than 82.71% of JavaScript online submissions for Binary Tree Level Order Traversal.
    Memory Usage: 40.9 MB, less than 7.95% of JavaScript online submissions for Binary Tree Level Order Traversal.

    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val, left, right) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.left = (left===undefined ? null : left)
    6. * this.right = (right===undefined ? null : right)
    7. * }
    8. */
    9. /**
    10. * @param {TreeNode} root
    11. * @return {number[][]}
    12. */
    13. var levelOrder = function(root) {
    14. if (!root) {
    15. return [];
    16. }
    17. const result = [];
    18. const queue = [root];
    19. let level;
    20. let node;
    21. let n;
    22. while(queue.length > 0) {
    23. level = [];
    24. n = queue.length;
    25. for (let i = 0; i < n; i++) {
    26. node = queue.shift();
    27. level.push(node.val);
    28. if (node.left) {
    29. queue.push(node.left);
    30. }
    31. if (node.right) {
    32. queue.push(node.right);
    33. }
    34. }
    35. result.push(level);
    36. }
    37. return result;
    38. };