# 剑指32-II 从上到下打印二叉树 II

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

给定二叉树: [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
# 返回结果
[
  [3],
  [9,20],
  [15,7]
]
 
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
    if(root == null) {
        return []
    }
    let steps = 0
    let queue = [root]
    let result = []
    while(queue.length) {
        let n = queue.length;
        result[steps] = []
        for(let i=0;i<n;i++) {
    
            const curNode = queue.shift()
            result[steps].push(curNode.val)
            if(curNode.left) queue.push(curNode.left)
            if(curNode.right) queue.push(curNode.right)
        }
        steps++
    }
    return result
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

时间复杂度是O(N),空间复杂度是O(N)