算法(TS):二叉树的层序遍历

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

示例一

输出:[[3],[9,20],[15,7]]

提示:

  • 树中节点数目在范围 [0, 2000] 内
  • -1000 <= Node.val <= 1000

解法

解法一

维护一个队列存放二叉树中的节点,同一层的节点从左到右连续放在一起。先将root放入队列,外层循环用while语句判断队列是否为空,将队列当前的长度保存在一个变量 size 中,size的值是本层节点的个数,内层循环用 while 判断size是否为0,在内层循环体中取出队首的节点node,将node的值push到需要返回的数据中,并将node.left 和 node.right push 到队尾。实现如下:

ts 复制代码
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function levelOrder(root: TreeNode | null): number[][] {
    if (!root) return []
    const stack: TreeNode[] = [root]
    const result: number[][] = []
    while(stack.length) {
        let size = stack.length
        const values:number[] = []
        while(size) {
            const node = stack.shift()
            values.push(node.val)
            if(node.left) {
                stack.push(node.left)
            }
            if (node.right) {
                stack.push(node.right)
            }
            size--
        }

        result.push(values)
    }

    return result
};

时间复杂度O(n),空间复杂度O(n)

解法二

用递归改造解法一。将解法一中的外层while和队列用递归代替

ts 复制代码
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function levelOrder(root: TreeNode | null): number[][] {
    const result: number[][] = []
    const conputed = (nodes: TreeNode[],values:number[][]) => {
        const levelValues: number[] = []
        const childrens: TreeNode[] = []
        while(nodes.length) {
            const node = nodes.shift()
            levelValues.push(node.val)
            if (node.left) {
                childrens.push(node.left)
            }
            if (node.right) {
                childrens.push(node.right)
            }
        }
        if (levelValues.length) {
            values.push(levelValues)
        }
        if (childrens.length) {
            conputed(childrens,values)
        }
    }

    if (root) {
        conputed([root],result)
    }
    return result
};

时间复杂度O(n),递归需要占用栈空间,空间复杂度O(height),height 是二叉树的最大深度

相关推荐
飞川撸码19 分钟前
【LeetCode 热题100】17:电话号码的字母组合(详细解析)(Go语言版)
算法·leetcode·golang·dfs
蒟蒻小袁20 分钟前
力扣面试150题--从前序与中序遍历序列构造二叉树
算法·leetcode·面试
闭月之泪舞1 小时前
初识函数------了解函数的定义、函数的参数、函数的返回值、说明文档的书写、函数的嵌套使用、变量的作用域(全局变量与局部变量)
python·算法·机器学习
GUIQU.2 小时前
【每日一题丨2025年5.12~5.18】排序相关题
算法·排序·每日一题
哪 吒2 小时前
2025B卷 - 华为OD机试七日集训第2期 - 按算法分类,由易到难,循序渐进,玩转OD(Python/JS/C/C++)
python·算法·华为od·华为od机试·2025b卷
孤寂大仙v2 小时前
【Linux笔记】——Linux线程封装
linux·笔记·算法
欧先生^_^3 小时前
Rust 编程语言的官方源码仓库
开发语言·算法·rust
程序员爱钓鱼3 小时前
可变参数(Variadic Functions)- 《Go语言实战指南》
算法
鸡鸭扣3 小时前
leetcode hot100:解题思路大全
数据结构·python·算法·leetcode·力扣
顾子茵3 小时前
游戏开发实战(一):Python复刻「崩坏星穹铁道」嗷呜嗷呜事务所---源码级解析该小游戏背后的算法与设计模式【纯原创】
python·算法·游戏