102. 二叉树的层序遍历

leetCode
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
    // 空数组就返回
    if (root === null) return []
    // 第一个入队
    let queue = [root]
    let result = []
    // 如果队列为空,说明已经遍历完成
    while(queue.length > 0) {
        // 获取当前层的元素个数
        let len = queue.length
        // 当前层的元素数组
        let arr = []
        // 遍历当前层的个数
        while(len > 0) {
            // 头指针删除,是当前层的
            let node = queue.shift()
            arr.push(node.val)
            len--
            // 将左右指针入队
            if (node.left) queue.push(node.left)
            if (node.right) queue.push(node.right)
        }
        // 当前层的输出到结果数组中
        result.push(arr)
    }
    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
33
34
35
36
37
38
39
更新时间: 2022-03-25 17:04