LeetCode199. Binary Tree Right Side View (思路及python解法)

LeetCode专项练习之树上宽度优先搜索(Tree Breadth-First Search)笔记 本文是根据穷码农的LeetCode刷题建议而进行专项练习时记录的心得。 最近发现自己练习时用的方法不太正确,老是想着自己先完全原创一个方法,实在写不动了才去看解析。这样做虽然有一定效果,但却非常耗时。其中,有一道中等题我前前后后花了6个小时才做完,结果发现自己之前做着做着就开始抠起了细节,完全没去用算法思想来解题,实在是得不偿失。以后,我不会再在一道题上死磕这么久了,在一个番茄钟的时间结束后... 阅读详情

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

这道题很简单,记录层序遍历后最右面的点。

层序遍历用BFS算法就很简单,然后保存每一层最后一个值就可以。用tempval保存每一层的val,tempnode保存每一层的node,final保存每一层最右面的一个val。

class Solution:
    def rightSideView(self, root: TreeNode) -> List[int]:
        if root is None: return root
        bfs=[root]
        final=[]
        
        while bfs:
            tempval=[node.val for node in bfs]
            final.append(tempval[-1])
            tempnode=[]
            for node in bfs:
                if node.left:
                    tempnode.append(node.left)
                if node.right:
                    tempnode.append(node.right)
            bfs = tempnode

        return final

 

【可信数据空间-连接器技术架构设计方案】 一句话概括连接器是可信数据空间的“数据保镖”和“外交官”。连接器就是一个部署在你本地的软件代理,它代表你安全地对外提供数据服务,确保在共享数据价值的同时,牢牢守住数据的所有权和控制权。它是实现“数据可用不可见”这一理想的关键技术部件。一个生动的比喻:银行的金库和接待员想象一下,你的数据就是藏在银行金库里的黄金和钞票。金库(你的内部数据库): 绝对安全,外人绝对不能进。接待员(连接器): 坐在银行大厅里,负责与客户打交道。客户向接待员提出请求:“我想取1000元。 阅读详情

相关推荐

Hive数据仓库分层架构实战:4层黄金模型×6大业务场景×万亿级数据优化方案

根据《2023数据中台成熟度报告》,‌78%的ETL任务性能瓶颈‌源于分层设计不合理。本文基于某头部电商平台PB级数据仓库建设经验,结合金融风控、用户画像、实时大屏等核心场景,深度解析‌ODS→DWD→DWS→ADS‌四层架构设计原则,揭秘‌万亿级数据治理方案‌与‌维度建模20大避坑策略‌。

CSDN博客专家,领域包括但不限于:AI、大数据、Python、架构师,有合作、课程、问题、疑惑请私信博主 1494

【LeetCode】199. Binary Tree Right Side View 解题报告(Python)

【LeetCode】199. Binary Tree Right Side View 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/binary-tree-right-side-view/description/ 题目描述: Given a binary tree, imagine yourself sta...

负雪明烛 3163

CAPL编程的催化剂——CAPLdll的实现

CANoe作为一款功能强大的总线开发及测试工具,不仅仅是因为其丰富的库函数,最重要的是其兼容了多种编程语言,可以实现灵活的开发,极大的解决了纯CAPL编程所带来的限制,如通过动态链接库(DLL)来实现复杂函数的编写,使其能够在CAPL中可以调用,下面将对DLL的实现进行分析。capldll.cpp这个文件初看相当复杂,从整体上来说,这段代码主要包含了两部分:自定义函数实现和回调函数定义,今天的主要任务是实现自定义函数,这里的函数定义与普通函数定义差不多,只是利用了CAPL的格式。在VS2017工程中打开。

车载控制器AutoSAR软件开发工程师 4656

二叉树的右视图 python_[LeetCode] 199. Binary Tree Right Side View 二叉树的右侧视图

Python: DFS# Time: O(n)# Space: O(h)class TreeNode(object):def __init__(self, x):self.val = xself.left = Noneself.right = Noneclass Solution(object):# @param root, a tree node# @return a list of inte...

weixin_32556315的博客 316

吉林大学软件工程章节测验 第九章 答案+解析

4.【判断题】估算软件规模有代码行技术和功能点技术两种方法,其中代码行方法估计实现一个功能所需要的源程序行数,其不依赖项目所使用的开发语言,并且具有较好的直观性。3.【单选题】软件项目估算时,若计划人员对每个功能分别按最佳的、可能的、悲观的三种情况给出功能点估计值,记作a, m, b,则估算的期望值E的公式为( )。8.【判断题】在工程网络图中,如果在由起始事件至终止事件所构成的一条路径上,所有事件的最早时刻都和最迟时刻都相同,那么这条路径就是关键路径。4.【单选题】配置管理贯穿软件开发的整个过程。

m0_51459931的博客 1437

深入解析Transformer三大注意力机制:自注意力、交叉注意力与因果自注意力

注意力机制是深度学习中的核心概念,它模拟了人类在处理信息时选择性聚焦的能力。其基本原理是通过计算查询与键的相似度,动态地为值分配权重,从而提取关键信息。这一机制解决了传统序列模型(如RNN)难以并行化和捕获长距离依赖的痛点,技术价值在于显著提升了模型的计算效率和表征能力。在自然语言处理、计算机视觉等应用场景中,注意力机制已成为构建强大模型的基石。本文聚焦于Transformer架构中的三种核心注意力变体:自注意力用于建立序列内部的全局关联,交叉注意力连接编码器与解码器的信息,而因果自注意力则确保自回归生成的

weixin_29094775的博客 433

Leetcode199. 二叉树的右视图 Binary Tree Right Side View - Python 以递归/迭代算法实现

注意不要看到是右视图,就忽略遍历左孩子if root.left: traversal(root.left, depth + 1)。2.在for循环体里,依次将每个节点的左右孩子(下一层节点)加入到queue,待下一轮while用;当一个根节点没有右孩子时,左孩子也能被看到。如此,无需遍历每层非最右侧的子节点的值,节约了时间复杂度。本题就是考察二叉树的层序遍历而已,没什么难的。迭代法层序遍历二叉树。

rendalian的博客 829

SAP CEWB 高效批量调整工艺路线与BOM的实战指南

本文详细介绍了SAP CEWB工具在批量调整工艺路线与BOM中的高效应用。通过实战案例和操作指南,帮助制造业企业快速掌握批量修改技巧,显著提升工作效率,避免手工操作带来的错误和耗时。特别适合需要频繁更新工艺路线和BOM的企业用户。

weixin_42524708的博客 405

Binary Tree Right Side View

Given a binary tree,imageine yourself standing on the right side of it,return the values of the nodes you can see orderd from top to bottom 1 &lt;--- / \ 2 3 &lt;--- \ ...

学习的路上,永不停止 280

【WorkBuddy专栏38】让AI帮你配环境——WorkBuddy编程环境配置完全指南

【WorkBuddy专栏38】让AI帮你配环境——WorkBuddy编程环境配置完全指南

AI人人懂 269

C#串口通信革命:RJCP.DLL.SerialPortStream实战全解析

本文介绍了如何通过RJCP.DLL.SerialPortStream库实现高性能串口通信解决方案。相比.NET自带的SerialPort类,该库提供了完全的异步非阻塞IO、动态缓冲区控制和多线程事件驱动等优势,特别适合工业自动化和物联网场景。文章详细讲解了环境搭建、核心功能对比,并通过代码示例展示了端口配置、异步通信管道搭建等关键技术。最后以Modbus RTU协议为例,演示了高级协议封装方法,为开发者提供了完整的工业级串口通信实现方案。

墨夶的博客 1891

[leetcode] 199. Binary Tree Right Side View @ python

原题 Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example: Input: [1,2,3,null,5,null,4] Output: [1, 3, 4...

闲庭信步 411

AI上推荐 之 AutoRec与Deep Crossing模型(改变神经网络的复杂程度)

1. 前言 随着信息技术和互联网的发展, 我们已经步入了一个信息过载的时代,这个时代,无论是信息消费者还是信息生产者都遇到了很大的挑战: 信息消费者:如何从大量的信息中找到自己感兴趣的信息? 信息生产者:如何让自己生产的信息脱颖而出, 受到广大用户的关注? 为了解决这个矛盾, 推荐系统应时而生, 并飞速前进,在用户和信息之间架起了一道桥梁,一方面帮助用户发现对自己有价值的信息, 一方面让信息能够展现在对它感兴趣的用户前面。 推荐系统近几年有了深度学习的助推发展之势迅猛, 从前深度学习的传统推荐模型(协

Miracle8070 5670

leetcode 199. Binary Tree Right Side View-树的右视图|递归|非递归|Java|Python

原题链接:199. Binary Tree Right Side View 【思路】非递归实现 层次遍历,每一层都是从左到右遍历,将每一层的最右一个节点添加到结果集中就是我们需要得到的结果: public class Solution { public List rightSideView(TreeNode root) { List res = new ArrayLi

hdtopku 2030

深度学习工具包 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")

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

leetcode 199. Binary Tree Right Side View

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example: Input: [1,2,3,null,5,null...

Weixu Liu的博客 168

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

【leetcode】199. Binary Tree Right Side View

19:43 题目描述: https://leetcode.com/problems/binary-tree-right-side-view/ 题目大意: 从右侧看一颗二叉树,看到的是哪些值? 解题思路: 基于广度优先搜索、双向列表的树层序遍历,每一层从左到右遍历,输出每一层最后一个元素。 python代码: # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, va

qq_36294507的博客 181

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

leetcode刷题笔记(Golang)--199. Binary Tree Right Side View

Binary Tree Right Side View Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example: Input: [1,2,3,null...

weixin_44555304的博客 215

LeetCode 199. 二叉树的右视图 Binary Tree Right Side View Python3解法

解题思路 采用DFS(深度优先遍历),遍历过程中对深度进行标记; 其次,为了得到右视图,先遍历节点的右子树,再遍历左子树 Python代码 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = N...

weixin_30793735的博客 387

二叉树的右视图 python_[LeetCode in Python] 199 (M) binary tree right side view 二叉树的右视图...

题目给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。示例:输入:[1,2,3,null,5,null,4]输出:[1, 3, 4]解释:1 /2 3 \5 4 解题思路BFS,按层遍历节点构造多层列表,将同层节点从左到右存于同一列表返回结果时,取每层列表的最后一个即可代码# Defini...

weixin_39693295的博客 111

[和小菜鸡一起刷题(python)] LeetCode 199. 二叉树的右视图. (Binary Tree Right Side View)

LeetCode 199. 二叉树的右视图(Binary Tree Right Side View)原题思路代码 原题 给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。 示例: 输入: [1,2,3,null,5,null,4] 输出: [1, 3, 4] 解释: 1 <--- / \ 2 3 ...

菜鸡也有鸿鹄志 338

二叉树层序遍历与算法优化实战指南

二叉树作为基础数据结构,其遍历方式是算法设计的核心基础。层序遍历采用队列实现广度优先搜索,时间复杂度为O(n),在解决层级相关问题时具有独特优势。通过维护level_size变量,可以精确控制每层节点的处理逻辑,这种模式广泛应用于最短路径计算、树形结构分析等场景。针对工程实践中的性能需求,Morris遍历和迭代法能有效优化空间复杂度,而二叉搜索树的有序特性则为范围查询提供了O(logn)的高效解决方案。在数据压缩领域,哈夫曼树通过频率统计构建最优前缀码,大幅提升存储效率。掌握这些二叉树核心算法及其变体,是应

weixin_30512089的博客 405

199. Binary Tree Right Side View Leetcode Python

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. For example: Given the following binary tree,# Defini

hyperbolechi的专栏 1284

【LeetCode】Binary Tree Right Side View 解题报告

【题目】 Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. For example: Given the following binary tre

跳出温水的青蛙 9210

Leetcode: Binary Tree Right Side View

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.For example: Given the following binary tree, 1

PacMan的专栏 502

python leetcode 199. Binary Tree Right Side View

层次遍历取最右 class Solution(object): def rightSideView(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] st...

Neekity的博客 696
上一篇: LeetCode127. Word Ladder (思路及python解法)
下一篇: LeetCode200. Number of Islands (思路及python解法)
船桥
博客等级 码龄9年 5粉丝 194原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值