徐徐爱coding
  • 首页
  • 爱情买卖
  • 导航
  • 私语
  • 友情链接
  • 关于
    关于本站
    知识库
    弹钢琴
徐徐爱coding

徐徐爱coding

徐徐爱coding是一个个人博客站点,记录编程经历的点点滴滴,分享自己的所见与所得,坚持自己的初心,践行自己的梦想生活不是等着暴风雨过去,而是学会在风雨中跳舞!

Copyright © 2023 徐徐爱coding All Rights Reserved.
陕公网安备61019602000456陕ICP备2023007787号-2

网站已稳定运行

二叉树层次遍历

二叉树层次遍历

徐徐
算法
#数据结构
4 热度0 评论0 点赞
发布于2023-09-24 20:39:19
🌺前言
一个简单的二叉树层次遍历算法

javascript
// @lc code=start
/**
 * 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) {
    let res = []
    if(!root) return res
    let queue = [root]
    while (queue.length) {
        let arr = []
        let len = queue.length
        for(let i = 0;i<len;i++){
            let node = queue.shift()
            arr.push(node.val)
            node.left&&queue.push(node.left)
            node.right&&queue.push(node.right)
        }
        res.push(arr)
    }
    return res
};
文章最后更新于 2024-08-17 01:21:06
作者:徐徐
版权声明:转载请注明文章出处
留言
暂无数据

~~空空如也