[Leetcode][python]Binary Tree Zigzag Level Order Traversal

【leetcode-Python】-103. Binary Tree Zigzag Level Order Traversal 题目链接 https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ 题目描述 给定一棵二叉树,返回树的zigzag层次遍历结果(当前层从左向右遍历,下一层就从右向左遍历......)。 示例 给定二叉树: 3 / \ 9 20 / \ 15 7 返回的zigzag层次遍历结果为: [ [3], [20,9], [15,7] ] 解决思路一 这道题类似 阅读详情

题目大意

按之字形遍历二叉树(一正一反)

解题思路

来自:链接
解题思路:这道题和上一题层序遍历那道题差不多,区别只是在于奇数层的节点要翻转过来存入数组。
代码:

代码

BFS

class Solution(object):
    def zigzagLevelOrder(self, root):
        tree = []
        if not root:
            return tree
        curr_level = [root]
        direction = 'L'
        # print(type(root), type(curr_level))  # (<class 'precompiled.treenode.TreeNode'>, <type 'list'>)
        # print(curr_level)  # 作为list,却并不能遍历整个树
        while curr_level:
            level_list = []
            next_level = []
            for temp in curr_level:
                level_list.append(temp.val)
                if temp.left:
                    next_level.append(temp.left)
                if temp.right:
                    next_level.append(temp.right)
            if direction == 'L':
                tree.append(level_list)
                direction = 'R'
            else:
                tree.append(level_list[::-1])
                direction = 'L'
            curr_level = next_level
        return tree

DFS

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

class Solution:
    # @param root, a tree node
    # @return a list of lists of integers
    def preorder(self, root, level, res):
        if root:
            if len(res) < level+1: res.append([])
            if level % 2 == 0: res[level].append(root.val)
            else: res[level].insert(0, root.val) # 向0位置插入
            self.preorder(root.left, level+1, res)
            self.preorder(root.right, level+1, res)
    def zigzagLevelOrder(self, root):
        res=[]
        self.preorder(root, 0, res)
        return res

总结

  1. insert()方法语法:
    list.insert(index, obj)
    参数
    index – 对象 obj 需要插入的索引位置。
    obj – 要插入列表中的对象。
  2. tree.append(level_list[::-1])将数组倒序插入
从零上手HiAgent:构建能听懂指令的智能体框架实战指南 智能体(Agent)作为人工智能领域的重要范式,正从传统的预设流程自动化转向以目标驱动的自主规划与执行。其核心原理在于利用大语言模型(LLM)作为决策大脑,通过任务规划、工具调用与记忆机制,将模糊的自然语言指令转化为可执行的工作流。这一技术显著提升了人机协作的效率和自然度,其价值在自动化办公、数据分析与智能流程编排等场景中尤为突出。本文聚焦于HiAgent这一具体框架,深入解析其作为智能体开发平台的核心架构,涵盖规划器、执行器、工具集等关键组件,并提供从环境配置、自定义工具开发到复杂任务链构建的完整工程实践 阅读详情

相关推荐

R语言分类变量的统计描述

三篇介绍了连续变量的统计描述的R语言相关函数,计算数值的相关统计指标。本文介绍分类变量的统计描述及如何在R语言中实现。 不同于连续变量,分类变量的统计描述主要是汇总分类变量各类别例数及百分比。 1、table()函数 ...

zsc943290710的博客 1万+

Binary Tree Zigzag Level Order Traversal

层次遍历、判断并获得每一层的实际节点个数、将一棵二叉树按照Z字形层次输出。

不积跬步无以至千里 247

Android Termux 安装Kali Linux 或 kali Nethunter史诗级详细教程

Termux 安装kali

风云小虾米的博客 6万+

[LeeCode] 103. Binary Tree Zigzag Level Order Traversal (Python 层序遍历、先序遍历 )

103.Binary Tree Zigzag Level Order Traversal Medium Given a binary tree, return thezigzag level ordertraversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree...

热爱编程,热爱技术 284

OpenWRT软件源更换保姆级教程:从国内镜像到官方源一键切换(含常见报错解决)

本文提供OpenWRT软件源更换的详细教程,涵盖从国内镜像源到官方源的切换方法,并深度解析常见报错解决方案。针对国内网络环境,指导用户如何精准定位系统信息、备份配置、选择并配置清华等国内镜像源,以及处理签名验证失败、依赖缺失、404错误等典型问题,旨在提升软件包管理效率与稳定性。

weixin_29229261的博客 2000

Ubuntu 24.04.3 LTS 安装 OpenClaw 图文版

OpenClow安装指南

qq_17204557的博客 2570

[leetcode] 103. Binary Tree Zigzag Level Order Traversal @ python

原题 Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary t...

闲庭信步 555

LangGraph实战训练营-从零构建AI驱动的wiki知识库

本文深入解析 LangChain 团队开源的 Deep Agents 框架核心示例——LLM Wiki,一个基于大语言模型自动构建和维护持久化知识库的生产级 AI Agent 系统。文章从项目架构、环境搭建、核心原理到实战操作全面展开:详解 CompositeBackend 组合后端与细粒度权限控制的安全设计、四种工作模式(初始化/摄取/查询/质量检查)的完整流程、LangSmith 远程沙箱的隔离执行机制,以及人机协同审核(HITL)的实践应用。

program哲学 213

[leetcode][python] 103. Binary Tree Zigzag Level Order Traversal

103. Binary Tree Zigzag Level Order Traversal 知识点:slack 1. 原题 Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the ne...

qq_40670635的博客 295

【云原生技术】helm中Chart.yaml、values.yaml、_helpers.tpl 各自的写法与作用

Chart.yaml、values.yaml、_helpers.tpl 各自的写法与作用 在一个标准的 Helm Chart 中,通常会包含以下关键文件: - **Chart.yaml** - **values.yaml** - **templates/`_helpers.tpl`** - 以及若干模板文件(`deployment.yaml`、`service.yaml` 等) 下面分别介绍这几个文件的作用、常见字段及其含义。

weixin_46453070的博客 760

lammps 案例in文件汇总

进阶案例: 聚乙烯和石墨烯界面pull out模拟代码 反应力场reax/c设置方法及案例解析 石墨烯热导率模拟代码(NEMD方法) 圆锥形SiC纳米磨削单晶硅源代码 高熵合金FeNiCrCoCu纳米压痕模拟代码 fix indent命令实现纳米摩擦及摩擦力计算 Fe原子辐照轰击多层石墨烯模拟代码 铝基石墨烯复合物压缩变形in文件源代码 石墨烯自动卷曲到Fe纳米线模拟源代码 铝/石墨烯复合物结晶过程lammps模

lammps_jiayou的博客 9451

103. Binary Tree Zigzag Level Order Traversal Leetcode Python

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binar

hyperbolechi的专栏 760

基于STM32的智能宠物喂食系统设计与实现(代码+PCB )

STM32;DHT11;本系统的软件程序基于Keil MDK-ARM V5集成开发环境进行编写和编译。Keil MDK是ARM公司官方推荐的嵌入式开发工具,支持ARM Cortex-M系列微控制器的程序开发,内置ARM C/C++编译器、调试器和仿真器,具有代码编辑、语法高亮、工程管理和在线调试等功能,是STM32开发领域应用最为广泛的IDE之一。

3254968421的博客 85

【leetCode】Binary Tree Zigzag Level Order Traversal python实现

Binary Tree Zigzag Level Order Traversal原题链接Binary Tree Zigzag Level Order Traversal实现原理解析 层次遍历即可,对于偶数层的做反向 python代码实现import copy# Definition for a binary tree node. # class TreeNode(object): # d

王伴农 1374

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

【LeetCode】103. Binary Tree Zigzag Level Order Traversal 解题报告(Python)

题目分析: 给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。 例如: 给定二叉树 [3,9,20,null,null,15,7], 返回锯齿形层次遍历如下: [[3],[20,9],[15,7]] 解题思路:、 这一题本质还是遍历,使用递归进行遍历。关键就是用一个变量去储存当前层数res[level].append(roo...

L141210113的专栏 1059

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

【Python3】 LeetCode 7月挑战题目之22 - Binary Tree Zigzag Level Order Traversal

目录/Table of Content第二十二天问:Binary Tree Zigzag Level Order Traversal题目&示例 (引用自 LeetCode)解题思路代码 (已提交,通过) 第二十二天问:Binary Tree Zigzag Level Order Traversal 这次题目要求要对二叉树进行锯齿形层次遍历 (Zigzag Level Order Traversal)。意思就是,现在这二叉树每个节点只包含一个整数,然后从顶层开始遍历,以次先从左往右,到下一层遍历再从右

骑著代码,看世界百态 188

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

LeetCode103. Binary Tree Zigzag Level Order Traversal (思路及python解法)

Given a binary tree, return thezigzag level ordertraversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tre...

AIpush的博客 288

python写算法题:leetcode: 103. Binary Tree Zigzag Level Order Traversal

class Solution(object): def traversal(self, node, ret, level): if node==None: return if len(ret)<=level: ret.append([]) if level&1==1: ret[...

182

[leetcode]Binary Tree Zigzag Level Order Traversal @ Python

原题地址:http://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ 题意: Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then ri...

weixin_34159110的博客 94

[LeetCode]题解(python):103-Binary Tree Zigzag Level Order Traversal

题目来源:   https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ 题意分析:   Z字宽度遍历树。 题目思路:   这题可以用比较取巧的方法。首先获得宽度遍历的结果,然后将第二层的翻转就可以了。 代码(python):    # Definition ...

weixin_34176694的博客 235

[LeetCode Python3] 103. Binary Tree Zigzag Level Order Traversal + 两种解法

103. Binary Tree Zigzag Level Order Traversal S1: # V1 class Solution: def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return None res, restmp = [], [] stack0, stack1 = [root], []

xvrixingkong的博客 237

Leetcode_binary-tree-zigzag-level-order-traversal (updated c++ and python version)

地址:http://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right

x 838

Leetcode 103. Binary Tree Zigzag Level Order Traversal 二叉树Zigzag遍历 解题报告

1 解题思想首先这道题和 Leetcode 102. Binary Tree Level Order Traversal 二叉树按层遍历 解题报告 很接近,Zigzag同样是按层遍历,但是区别是对于高度为奇数(从0开始计数的话,则是第1 3 5 7)的层,当层的遍历需要反过来。做法: 1、采用102题目中的方式,无论是DFS还是BFS都行 2、完成1后,对所有奇数层进行翻转这题的写法和102

MebiuW的专栏 1863

[LeetCode] 103. Binary Tree Zigzag Level Order Traversal

题目链接: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/ DescriptionGiven a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to

从入门到扑街 498

[LeetCode]Binary Tree Zigzag Level Order Traversal@Python

Binary Tree Zigzag Level Order Traversal Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternat...

byr_wy的博客 266
上一篇: [Leetcode][Python/Java]Binary Tree Level Order Traversal/二叉树层序遍历
下一篇: [Leetcode][python]Maximum Depth of Binary Tree/二叉树的最大深度
蛮三刀酱
蛮三刀酱 领域专家: 算法与数据结构技术领域 领域专家: 算法与数据结构技术领域
博客等级 码龄15年 5541粉丝 310原创
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值