给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)
    3
    / \
    9 20
    / \
    15 7
    [
    [3],
    [9,20],
    [15,7]
    ]

    1. //先利用广度优先遍历
    2. var levelOrder = function(root) {
    3. if (!root) return []
    4. const q = [root]
    5. while(q.length){
    6. const n = q.shift()
    7. console.log(n.val)
    8. if(n.left) q.push(left)
    9. if(n.right) q.push(right)
    10. }
    11. }
    1. //记录层级
    2. var levelOrder = function(root) {
    3. if (!root) return []
    4. const q = [[root, 0]]
    5. while(q.length){
    6. const [n,level] = q.shift()
    7. console.log(n.val, l)
    8. if(n.left) q.push([n.left, level+1])
    9. if(n.right) q.push([n.right, level+1])
    10. }
    11. }
    12. //push 数组里
    13. var levelOrder = function(root) {
    14. if (!root) return []
    15. const q = [[root, 0]]
    16. let res = []
    17. while(q.length){
    18. const [n,level] = q.shift()
    19. if(!res[level]){
    20. res.push([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. }
    29. //方法二
    30. var levelOrder = function(root) {
    31. if (!root) return []
    32. const q = [root]
    33. const res = []
    34. while(q.length){
    35. let len = q.length;
    36. res.push([]);
    37. while(len--){
    38. const n = q.shift()
    39. res[res.length-1].push(n.val)
    40. if(n.left) q.push(n.left)
    41. if(n.right) q.push(n.right)
    42. }
    43. }
    44. return res
    45. }