优先广度优先遍历
    遍历过程中,记录每个每个节点的层级,并将其添加到不同的数组中去

    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) return [];
    15. const q = [[root, 0]];
    16. const res = [];
    17. while(q.length) {
    18. const [n, level] = q.shift();
    19. if(!res[level]) {
    20. res[level] = [n.val];
    21. } else {
    22. res[level].push(n.val);
    23. }
    24. if(n.left) q.push([n.left, level + 1]);
    25. if(n.right) q.push([n.right, level + 1]);
    26. }
    27. return res;
    28. };

    优化空间:将队列中属于同一层级的数据,一次性的添加到数组中。

    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) return [];
    15. const q = [root];
    16. const res = [];
    17. while(q.length) {
    18. res.push([])
    19. let length = q.length;
    20. while(length--) {
    21. const n = q.shift();
    22. res[res.length-1].push(n.val)
    23. if(n.left) q.push(n.left);
    24. if(n.right) q.push(n.right);
    25. }
    26. }
    27. return res;
    28. };