数据结构与算法之二叉树: LeetCode 102. 二叉树的层序遍历 (Ts, Py, Go版)

MIMIC数据库基本信息分析 一、MIMIC数据库中26张表介绍 数据库中一共有26张表,记录患者入院的各种信息,每张表的介绍如下所示。 表格名 信息 admission 患者基本信息,比如性别、种族、语言、宗教、婚姻、入院和出院时间、死亡时间等 callout 提供病人准备从ICU转出或者已经从ICU转出时相关信息 caregivers 记录医护人员信息(ID、类型、附加... 阅读详情

二叉树的层序遍历

  • https://leetcode.cn/problems/binary-tree-level-order-traversal/

描述

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

示例 1

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

示例 2

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

示例 3

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

提示

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

Typescript 版算法实现


1 )方案 1

/**
 * 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 [];
    let q:[TreeNode | null, number][] = [[root, 0]];
    const res = [];
    while(q.length) {
        let [n, l] = q.shift();
        // 一开始数组存放的是[root, 0], 下标为0, 直接存入当前层级的值,root
        if(!res[l]) {
            res.push([n.val]);
        } else {
            res[l].push(n.val); // 将当前层级的值push进去
        }
        // cosnole.log(n.val);
        n.left && q.push([n.left, l+1]);
        n.right && q.push([n.right, l+1]);
    }
    return res
}
  • 思路
    • 层序遍历就是广度优先遍历
    • 在遍历的时候,要记录当前节点所处层级,方便将其添加到不同的数组中
  • 步骤
    • 广度优先遍历,使用队列
    • 遍历中,记录每个节点层级,并将其添加到不同的数组中
  • 总结
    • 上述借助了一个队列q来实现所有节点的存储
    • 通过一个层级l的记录,遍历所有队列中的节点来基于l来访问当前层的数据
    • 而且注意这个顺序一定是先左后右

2 )方案 2

/**
 * 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)
 *     }
 * }
 */

// 优化版
// 在while循环中,老人出队,新人全部入队
function levelOrder(root: TreeNode | null): number[][] {
    if(!root) return [];
    let q = [root];
    const res = [];
    while(q.length) {
        let len = q.length;
        res.push([]);
        // 执行一次老人出队,并把它的孩子节点入队,完成新陈代谢
        // 保证进入第一个while时,全都是同一层级的节点入队
        while(len--) {
            let n = q.shift();
            res[res.length - 1].push(n.val); // 拿到当前层的数据,将当前层的节点值都存入新数组
            n.left && q.push(n.left);
            n.right && q.push(n.right);
        }
    }
    return res
}
  • 这个是方案1的优化版,内层的while循环保证了将同一层的节点都推入到了一个数组中保存
  • 这样就省去了方案1中保存当前层级l之后,基于l来push节点了,这样效率会更高一些

3 )方案 3

/**
 * 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 ret = [];
    if (!root) {
        return ret;
    }
    const q = [];
    q.push(root);
    while (q.length) {
        const currentLevelSize = q.length;
        ret.push([])
        for (let i = 1; i <= currentLevelSize; i++) {
            const node = q.shift();
            ret[ret.length - 1].push(node.val);
            if (node.left) q.push(node.left);
            if (node.right) q.push(node.right);
        }
    }
    return ret;
}
  • 这是官方示例,就是方案2的变形,原理是一样的

Python3 版算法实现


1 ) 方案1:迭代版(BFS)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        q = deque([(root, 0)])
        res = []
        while q:
            n, l = q.popleft()
            if l == len(res):
                res.append([n.val])
            else:
                res[l].append(n.val)
            if n.left:
                q.append((n.left, l + 1))
            if n.right:
                q.append((n.right, l + 1))
        return res

2 )方案2:迭代版(BFS)另一种实现

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        q = deque([root])
        res = []
        while q:
            len_q = len(q)
            res.append([])
            for _ in range(len_q):
                n = q.popleft()
                res[-1].append(n.val)
                if n.left:
                    q.append(n.left)
                if n.right:
                    q.append(n.right)
        return res

3 )方案3:迭代法(BFS)优化版

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        ret = []
        if not root:
            return ret
        q = deque([root])
        while q:
            current_level_size = len(q)
            ret.append([])
            for _ in range(current_level_size):
                node = q.popleft()
                ret[-1].append(node.val)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
        return ret

Golang 版算法实现


1 ) 方案1: 迭代版(BFS)

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

func levelOrder(root *TreeNode) [][]int {
	if root == nil {
		return [][]int{}
	}
	queue := [][2]interface{}{{root, 0}} // 队列传递根节点和层级
	res := [][]int{}
	for len(queue) > 0 {
		n, l := queue[0][0].(*TreeNode), queue[0][1].(int) // 取出队首元素和层级
		queue = queue[1:]
		if l == len(res) {
			res = append(res, []int{n.Val})
		} else {
			res[l] = append(res[l], n.Val)
		}
		if n.Left != nil {
			queue = append(queue, [2]interface{}{n.Left, l + 1})
		}
		if n.Right != nil {
			queue = append(queue, [2]interface{}{n.Right, l + 1})
		}
	}
	return res
}

2 ) 方案2: 迭代版(BFS)另一种实现

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

func levelOrder(root *TreeNode) [][]int {
	if root == nil {
		return [][]int{}
	}
	queue := []*TreeNode{root}
	res := [][]int{}
	for len(queue) > 0 {
		lenQueue := len(queue)
		res = append(res, []int{})
		for i := 0; i < lenQueue; i++ {
			n := queue[0]
			queue = queue[1:]
			res[len(res)-1] = append(res[len(res)-1], n.Val)
			if n.Left != nil {
				queue = append(queue, n.Left)
			}
			if n.Right != nil {
				queue = append(queue, n.Right)
			}
		}
	}
	return res
}

3 ) 方案3: 迭代版(BFS)优化版

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

func levelOrder(root *TreeNode) [][]int {
	ret := [][]int{}
	if root == nil {
		return ret
	}
	queue := []*TreeNode{root}
	for len(queue) > 0 {
		currentLevelSize := len(queue)
		ret = append(ret, []int{})
		for i := 1; i <= currentLevelSize; i++ {
			node := queue[0]
			queue = queue[1:]
			ret[len(ret)-1] = append(ret[len(ret)-1], node.Val)
			if node.Left != nil {
				queue = append(queue, node.Left)
			}
			if node.Right != nil {
				queue = append(queue, node.Right)
			}
		}
	}
	return ret
}
vue中使用video-player视频插件,第一次无法监听父组件穿过来的值解决办法 需求: 页面![在这里插入图片描述](https://img-blog.csdnimg.cn/20201208141906802.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0FfOTg4OA==,size_16,color_FFFFFF,t_70) 作品清单是从后端请求回来的不同格式的url,前端需求根据后缀动态判断格式,然后对齐进行下载和 阅读详情

相关推荐

Isograph Reliability Workbench 14实战:从零构建故障树分析模型

本文以“马达不转”为例,手把手教你使用Isograph Reliability Workbench 14从零构建故障树分析模型。内容涵盖创建工程、定义顶事件、添加逻辑门与基础事件等核心步骤,并介绍了模型检查与定性定量分析,帮助你系统掌握这一强大的可靠性工程工具。

weixin_29309213的博客 365

leetcode每日一练-第102题-二叉树的层序遍历

通过广度优先搜索(BFS)的方式,按层遍历二叉树节点,并将每层的节点值保存在一个一维数组中,然后再将所有的一维数组存储在二维数组中,最后返回二维数组作为层序遍历的结果。BFS(广度优先搜索)和DFS(深度优先搜索)是两种。,它们在搜索问题中有不同的应用和特点。寻找所有可能的路径或找到特定路径。适用于树或图中需要按层遍历节点。常见的图和树遍历算法。栈数据结构(或递归)

weixin_48820672的博客 545

【Python】SimpleITK使用笔记

1. 概念 1.1 nii格式 1.2 SimpleITK 1.3 SimpleITK 图像 2. 基本操作 2.1 常见属性 2.1 读取和保存图像 2.2 SimpleITK图像数据和Numpy矩阵数据之间的转换

See_Star的博客 7900

leetcode 102 二叉树的层序遍历 思路与C Python实现

leetcode 队列

Artist351的博客 363

QFN封装芯片手工焊接实战:从焊盘处理到拖焊技巧

本文详细介绍了QFN封装芯片手工焊接的全过程,从焊盘处理到拖焊技巧,再到常见问题的现场修复方法。通过实战经验分享,帮助工程师和DIY爱好者掌握0.5mm小间距QFN芯片的焊接技术,提升焊接成功率和质量。重点讲解了垂直与平行拖焊手法的对比应用,以及焊后清理与质量检验的关键步骤。

weixin_42652674的博客 533

Eclipse在Mac上报错JNI_CreateJavaVM?可能是你的JDK架构搞错了(附Adoptium JDK下载指南)

本文深入解析了Mac(尤其是Apple Silicon芯片)上Eclipse启动时出现“JNI_CreateJavaVM”错误的根本原因,即JDK架构(aarch64与x86_64)不匹配。文章提供了详细的诊断步骤,并推荐通过下载并配置Eclipse Adoptium提供的aarch64版本JDK来彻底解决问题,同时附上清晰的配置指南。

weixin_29065659的博客 321

二叉树层次遍历--python

二叉树层次遍历–python 队列实现 # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrder(self, r

AberamaGold的博客 301

Transformer实战(40)——Transformer时间序列数据建模

Transformer 因其在自然语言处理 (Natural Language Processing, NLP) 任务中的优异表现而被广泛应用,其主要优势在于能够有效建模时间序列数据。这些数据可以是文本,也可以是非文本。本节将介绍如何使用 Transformer 进行时间序列数据建模和预测,将学习时间序列的基本概念,并在此基础上使用一个简单的模型,用以初步了解时间序列数据,并为各种预测任务奠定基础。

盼小辉丶的博客 2413

LeetCode102_102. 二叉树的层序遍历

LeetCode102_102. 二叉树的层序遍历

luoyepiaoxue2014的博客 1904

裂缝二维检测:裂缝的长度和宽度检测

这一节,我们需要去整合一下前面的代码,在进行长度和宽度的测量时,需要裂缝的类型、个数、面积的帮助。这一章是本专栏的核心部分。以上代码我均试过,由于本人能力有限,看不懂代码,最终还是没有采用,使用的是最普通检测宽度的方法,即求得骨架总长度后,用总面积求取平均宽度。

m0_62919535的博客 4242

注意力机制模块:二次创新:CBAM 与 ECA 融合形成 CECA 模块,参数量减少 40%

文章摘要: 本文提出一种轻量化注意力模块CECA,通过融合CBAM和ECA的优势解决模型部署中的精度与速度矛盾。CBAM虽具备通道和空间双重注意力,但参数量大;ECA轻量但缺乏空间注意力。CECA采用ECA的一维卷积替换CBAM的通道注意力部分,保留其空间注意力模块,在保持双注意力能力的同时减少40%参数量。实验表明该方案在边缘设备部署中能维持精度并提升推理速度,特别适用于YOLO等目标检测模型的轻量化改进。文章详细拆解了架构设计、代码实现及参数量优化原理,为算法工程师和嵌入式开发者提供了实用解决方案。

ZXSXJ的博客 237

Leetcode: 102. 二叉树的层序遍历

描述 给你一个二叉树,请你返回其按层序遍历得到的节点值。 (即逐层地,从左到右访问所有节点)。 示例 二叉树:[3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回其层次遍历结果: [ [3], [9,20], [15,7] ] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal ..

yz_yz1234的博客 339

第9.3章 从CMake基础到自动驾驶实战:构建跨平台C/C++项目的全能指南

《CMake构建实战:项目开发卷》精要指南 本文系统梳理了许宏旭《CMake构建实战》核心内容,涵盖C++构建全流程: 基础构建:详解MSVC/GCC编译器使用、Makefile编写及静态/动态库构建方法 CMake核心:解析语法结构、变量控制、文件操作等关键命令,阐述项目全生命周期管理 实战应用:通过快速排序、手写数字识别项目演示现代CMake实践,特别针对自动驾驶领域给出多传感器融合、SLAM等场景的CMake配置方案 特色价值:本书填补了官方文档实例不足的空白,提供300+代码示例,是掌握工业级C++

行知SLAM 1344

【LeetCode】102. 二叉树的层序遍历

题目:102. 二叉树的层序遍历 给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。 示例 1: 输入:root = [3,9,20,null,null,15,7] 输出:[[3],[9,20],[15,7]] 示例 2: 输入:root = [1] 输出:[[1]] 示例 3: 输入:root = [] 输出:[] 提示: 树中节点数目在范围 [0, 2000] 内 -1000 <= Node.val <= 1000 解题思路 使用队

ZhShy 1024

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【LeetCode】102.二叉树的层序遍历

LeetCode 第102题 二叉树的层次遍历

kezade的blog 1031

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

LeetCode 102题解 | 二叉树的层序遍历

二叉树的层序遍历

2401_87255690的博客 987

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

[LeetCode][102]二叉树的层序遍历——遍历结果中每一层明显区分

给定二叉树的根节点root,返回节点值的层序遍历结果。即逐层地,从左到右访问所有节点。示例 1:输入:root = [3,9,20,null,null,15,7] 输出:[[3],[9,20],[15,7]]示例 2:输入:root = [1] 输出:[[1]]示例 3:输入:root = [] 输出:[]提示:树中节点数目在范围 [0, 2000] 内。

Witheart 的博客。 620

Leetcode 102: 按层遍历二叉树, 112 路径总和问题

一、逐层遍历二叉树(中等) 题目 给你二叉树的根节点root,返回其节点值的层序遍历。 (即逐层地,从左到右访问所有节点)。 输入:root = [3,9,20,null,null,15,7] 输出:[[3],[9,20],[15,7]] 示例 2: 输入:root = [1] 输出:[[1]] 示例 3: 输入:root = [] 输出:[] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-le...

Dream_it_possible!的博客 1373

Leetcode102-二叉树的层序遍历详解

Leetcode102-二叉树的层序遍历详解-Python代码

白羊by的博客 511

图解LeetCode——102. 二叉树的层序遍历

那么每一层我们将其保存到一个List中,然后所有二叉树节点都遍历完毕后,就输出。,那么就无法区分哪些是一层的了。以上就是深度优先遍历的解题思路,为了便于理解,下面我们以输入root =写作不易,笔者几个小时甚至数天完成的一篇文章,只愿换来您几秒钟的。方式,去输出每个节点,处理方式就是首先我们来创建一个队列。的方式获得这个层级的节点值集合。,用于暂存遍历的节点。中没有创建该层集合,则创建,然后将节点的。根据题目要求,我们要实现二叉树的。为例,看一下具体的处理过程。为例,看一下具体的处理过程。

爪哇缪斯的博客 547

LeetCode第102题---二叉树的层序遍历

LeetCode链接: link. 解题思路: ① 在这里插入代码片 LeetCode第107题—二叉树的层序遍历II链接: link. 这道题和上面的题思想一致,就是需要在把vector<vector< int>> 里面的vector< int>进行reverse逆置就可以了。 ...

MEANSWER的博客 286

LeetCode-102.题: 二叉树的层序遍历(原创)

这道理的关键点在于“自顶向下,一层接一层交替访问树节点”; 算法设计时,可以考虑最简单的情况,试探思考其运行逻辑应该是什么样的 还是要有精细化的逻辑思维,层次分明,这样在复杂的逻辑也不会乱;

it_fly的专栏 857

LeetCode-102 层次遍历

一、思路 这道题使用的是二叉树的广度优先遍历,也就是层次遍历。与单纯的层次遍历不同的地方在于,这个问题要求返回的遍历结果是一个二维数组,一行代表树的一层。但是总的思路还是和层次遍历没有区别。 为了知道二叉树中每一个节点位于书的哪一层的问题,需要标识每一个节点所在的层数,并根据层次遍历时的节点,对其子节点进行标识。在这里我想到的方法有两种:第一种是建一个队列保存节点的层数,与层次遍历的队列保持一一对...

qq_43575926的博客 180

LeetCode:102. 二叉树的层序遍历

LeetCode:102. 二叉树的层序遍历 _ 递归、迭代法 _ 你会建立一棵二叉树吗? 给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

Super algorithm 的博客,技术爱好者。 1089

算法第一天:力扣(LeetCode) LCR 102.目标和

基本明确了dp数组的定义,就可以确定状态转移了。

m0_75068978的博客 847

每日一题:Leetcode-102 二叉树的层序遍历

力扣题目解题思路java代码。

LIUCHANGSHUO的博客 555
上一篇: 数据结构与算法之二叉树: LeetCode 111. 二叉树的最小深度 (Ts, Py, Go版)
下一篇: 数据结构与算法之二叉树: LeetCode 112. 路径总和 (Ts, Py, Go版)
Wang's Blog
博客等级 码龄12年 7438粉丝 2421原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wang's Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值