leecode102. 二叉树的层序遍历

58 阅读1分钟

前言

记录一下算法的学习

题目描述

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

示例1

image.png

输入: root = [3,9,20,null,null,15,7]
输出: [[3],[9,20],[15,7]]

示例2

输入: root = [1]
输出: [[1]]

示例3

输入: root = []
输出: []

解析

  1. 根据题解,从左到右依次遍历节点
  2. 可以得出使用广度优先遍历

代码编写

/**
 * 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) return []
    // 存一个变量代表层级
    const queue = [[root,0]]
    const res = []
    while(queue.length) {
        const [n,level] = queue.shift()
        if(!res[level]) {
            res.push([n.val])
        }else {
            res[level].push(n.val)
        }
        n.left && queue.push([n.left,level + 1])
        n.right && queue.push([n.right,level + 1])
    }
    return res
    
}

优化

可以通过一次存储一个层级的数据

var levelOrder = function(root) {
    if(!root) return []
    // 存一个变量代表层级
    const queue = [root]
    const res = []
    while(queue.length) {
        // 每次进入循环代表进入下一层级
        // 这里推入一个空数组
        res.push([])
        // 记录一个变量,用来记录剩余当前层级的节点长度
        let len = queue.length
        while(len--) {
            const n = queue.shift()
            // 取出最后一项,也就是当前层级的数组
            res[res.length - 1].push(n.val)
            n.left && queue.push(n.left)
            n.right && queue.push(n.right)
        }

    }
    return res
    
}

复杂度分析

  • 时间复杂度:需要遍历整个树,复杂度为树的节点数O(n)
  • 空间复杂度:需要维护一个数组,长度是线性增长复杂度为O(n)

最后

每天进步一点点