算法(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 是二叉树的最大深度

相关推荐
浅念-3 小时前
递归解题指南:LeetCode经典题全解析
数据结构·算法·leetcode·职场和发展·排序算法·深度优先·递归
Kiling_07043 小时前
Java集合进阶:Set与Collections详解
算法·哈希算法
智者知已应修善业4 小时前
【51单片机89C51及74LS273、74LS244组成】2022-5-28
c++·经验分享·笔记·算法·51单片机
洛水水4 小时前
【力扣100题】33.验证二叉搜索树
算法·leetcode·职场和发展
SimpleLearingAI4 小时前
聚类算法详解
算法·数据挖掘·聚类
刀法如飞5 小时前
Go 字符串查找的 20 种实现方式,用不同思路解决问题
算法·面试·程序员
Dlrb12117 小时前
C语言-指针数组与数组指针
c语言·数据结构·算法·指针·数组指针·指针数组·二级指针
WL_Aurora7 小时前
Python 算法基础篇之集合
python·算法
平行侠7 小时前
A15 工业路由器IP前缀高速检索与内存压缩系统
网络·tcp/ip·算法
阿旭超级学得完8 小时前
C++11包装器(function和bind)
java·开发语言·c++·算法·哈希算法·散列表