广度优先搜索

    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. let result = []
    16. let que = []
    17. que.push(root)
    18. while(que.length !== 0) {
    19. let init_size = que.length
    20. let temp = []
    21. for (let i = 0; i<init_size; i++) {
    22. let mp = que.shift()
    23. if(mp.left) que.push(mp.left)
    24. if(mp.right) que.push(mp.right)
    25. temp.push(mp.val)
    26. }
    27. result.push(temp)
    28. }
    29. return result
    30. };

    image.png